- Home /
How can I have good acceleration mechanics for a 2d spaceship? (C#)
I'm trying to recreate a ship that moves at 0g, but the AddForce argument doesn't follow the ship orientation. How can I get the "booster" effect where I can accelerate and decelerate with the vertical controls and the thrust is always behind the ship?
Here is the code I used: using UnityEngine; using System.Collections;
public class ControlloNave : MonoBehaviour {
public float RotV;
public float TravelV;
// Use this for initialization
void Start () {
Debug.Log("The movement script is loaded");
}
// Update is called once per frame
void Update () {
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
GetComponent<Rigidbody2D>().transform.Rotate(0, 0, moveHorizontal*RotV);
GetComponent<Rigidbody2D>().AddForce(moveVertical* transform.right * TravelV,ForceMode2D.Force);
}
}
If possible, I also aim to forbid the user from getting negative acceleration values (I don't want the ship to go backward).
Thanks for the help!
Answer by MD_Reptile · May 01, 2016 at 08:25 AM
GetComponent < Rigidbody2D >().AddRelativeForce(....);
That should do it, instead of using AddForce. Probably should keep a reference to that rigidbody2d instead of using GetComponent every time:
...
public float TravelV;
private Rigidbody2D thisRigidbody;
// Use this for initialization
void Start () {
Debug.Log("The movement script is loaded");
thisRigidbody = GetComponent < Rigidbody2D > ();
}
...
I replaced the argument, but now the ship moves in see$$anonymous$$gly random directions. How does AddRelativeForce work?
Your answer