- Home /
Rigidbody.MovePosition() moves only in the GLOBAL z axis (forward and backward)
Hi,
I am making a simple character controller script, and I am using Rigidbody to move my character. But my problem is that the character moves only forward and backward, which is the Global z axis. Even if I rotate my character around the y axis, it only moves forward and backward (global of course). I also tried to move the rigidbody using transform.localPosition instead of transform.position, but it also doesn't work.
What did I do wrong? Can someone help me please?
Here is my code:
public float moveSpeed = 50f;
public float rotateSpeed = 200f;
private Vector3 moveDir;
private float rotate;
public Rigidbody rb;
void Update()
{
moveDir = new Vector3(0, 0, Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime);
rotate = Input.GetAxis("Horizontal") * rotateSpeed * Time.deltaTime;
}
void FixedUpdate()
{
rb.MovePosition(transform.position + moveDir);
transform.Rotate(0, rotate, 0);
}
I am a beginner, but it looks when you rotate the player it doesn't change the direction of the z axis of the player, so it will only go forward and backward in the z axis
Answer by Casiell · Jun 24, 2020 at 05:37 PM
To get the translation in local space you need to multiply transform.Forward by your vector length
so your moveDir would be
transform.Forward * Input.GetAxis("Vertical") * moveSpeed * Time.deltaTIme
Thank you :D, it is worknig:
moveDir = transform.forward * Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
Your answer
Follow this Question
Related Questions
Vector 3 - move on only one axis 0 Answers
Lerp a Object along X and Z axis only. 3 Answers
How to lock X rotation; broken script 0 Answers
JS Move object over time 1 Answer