Question by
fancyfalcon · Jul 13, 2016 at 07:22 AM ·
unity 5rotationaddforce
Applying AddForce() while rotating player gameobject.
I made a player gameobject and a script for moving it forward and backwards + making it rotate left and right in a 2D game. I used AddForce() for the movement and transform.Rotate for the rotation. Here's the code:
public float moveForce;
public float drag;
public float rotSpeed;
void Update(){
if (Input.GetKey(KeyCode.W)){
GetComponent<Rigidbody2D> ().drag = 0;
GetComponent<Rigidbody2D> ().AddForce (Vector3.up * moveForce * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S)){
GetComponent<Rigidbody2D> ().drag = 0;
GetComponent<Rigidbody2D> ().AddForce (Vector3.up * -moveForce * Time.deltaTime);
}
if(Input.GetKey(KeyCode.W) == false && Input.GetKey(KeyCode.S) == false){
GetComponent<Rigidbody2D> ().drag = drag;
}
if (Input.GetKey (KeyCode.A)) {
transform.Rotate (Vector3.forward * rotSpeed * Time.deltaTime);
}
if (Input.GetKey (KeyCode.D)) {
transform.Rotate (-Vector3.forward * rotSpeed * Time.deltaTime);
}
}
AddForce works fine, so does the rotation, the only problem is that when the player is facing any other direction than the vertical one, AddForce doesn't follow the player's direction, but only moves the player up and down on the vertical one.
Comment