I followed this tutorial to create a planet with faux gravity that attracts objects.
Further I'm trying to create a helicopter-like controller that could move vertically and horizontally and that when the player presses control buttons this would compensate the faux gravity applied with AddForce
to Rigidbody
and the helicopter could fly. I implemented that in a way that when player presses buttons faux gravity with AddForce
is not applied, but still the control feels very awkward.
What would be the best way to compensate the faux gravity to move the helicopter?
Edit: I only need it to move in XY plane (so only up/down/left/right). The camera looks on helicopter from its right side. The attractor script works in 3 axis and this is ok for now.
Player controller (assigned to the helicopter):
public class PlayerController : MonoBehaviour {
public float moveSpeed = 15;
private Rigidbody rb;
private Vector3 moveDir;
private float h;
private float v;
void Awake() {
rb = GetComponent<Rigidbody>();
if(!rb) throw new Exception("Game Object must have Rigidbody!");
}
void Update () {
GetControls();
moveDir = new Vector3(h, v, 0).normalized;
}
void GetControls() {
h = Input.GetAxis("Horizontal");
v = Input.GetAxis("Vertical");
}
void FixedUpdate() {
rb.MovePosition(rb.position + transform.TransformDirection(moveDir) * moveSpeed * Time.deltaTime);
}
}
Faux Gravity Attractor (assigned to the planet):
public class FauxGravityAttractor : MonoBehaviour {
public float gravity = -10;
public void Attract(Transform body) {
Vector3 gravityUp = (body.position - transform.position).normalized;
Vector3 bodyUp = body.up;
Rigidbody bodyRb = body.GetComponent<Rigidbody>();
bodyRb.AddForce(gravityUp * gravity);
Quaternion targetRotation = Quaternion.FromToRotation(bodyUp, gravityUp) * body.rotation;
body.rotation = Quaternion.Slerp(body.rotation, targetRotation, 50 * Time.deltaTime);
}
}
Faux Gravity Body (assigned to the helicopter):
public class FauxGravityBody : MonoBehaviour {
[SerializeField]
float gravity = -10;
public FauxGravityAttractor attractor;
private Transform myTransform;
void Start () {
Rigidbody rb = GetComponent<Rigidbody>();
rb.constraints = RigidbodyConstraints.FreezeRotation;
rb.useGravity = false;
myTransform = transform;
}
void Update () {
attractor.Attract(myTransform);
}
}