- Home /
rigidbody local space problem
I've set the rigidbody to move according to local space instead of world space. However, when rotating the ship rotates it doesn't move to the y axis of the local coordinates according to the scene view instead it moves to the x axis of the local coordinates.
My code snippet:
public float speed;
public float rotationSpeed;
void Update(){
float horizontal = Input.GetAxis ("Horizontal");
//used to change the rotation of the ship
transform.eulerAngles += new Vector3 (0.0f, 0.0f, horizontal * -rotationSpeed * Time.deltaTime);
}
void FixedUpdate(){
float vertical = Input.GetAxis ("Vertical");
Vector2 movement = new Vector2 (0.0f,vertical);
//moves the ship in a local space
rigidbody2D.velocity = transform.InverseTransformDirection(movement * speed);
Debug.Log (movement);
}
Answer by Owen-Reynolds · Jun 16, 2014 at 05:50 PM
I think InverseTransformDirection should be TransformDirection. Local/global coord transforms can hurt your head. But, a more obvious way is using transform.forward
:
transform.forward
is your personal, local, length 1 blue arrow. So could set velocity = transform.forward*(vertical*speed);
. The parens aren't needed. I think this reads nicely as "move me forward, at that speed".
If someone else is setting speed, spaceship.forward
is the same thing (assuming spaceship is the spaceships's transform.)
Also, playing directly with EulerAngles (line 6) isn't recommended. It may work as long as no other angles change. transform.Rotate(0,0,...)
is the standard way. Then using Quaternions directly, for the weird stuff.
Thanks it worked finally. I've been trying to fix it for hours.And thanks for the tip I will keep that in $$anonymous$$d.
Your answer
![](https://koobas.hobune.stream/wayback/20220613151705im_/https://answers.unity.com/themes/thub/images/avi.jpg)