- Home /
How can I convert LOCAL transform.forward to WORLD Vector3?
Hi guys,
I'm using:
transform.Rotate(new Vector3(0, Input.GetAxis("Horizontal") * rotateSpeed * Time.deltaTime, 0.0f));
if(Input.GetKey(KeyCode.W)){
transform.position += transform.forward * speed * Time.deltaTime;
}
if(Input.GetKey(KeyCode.S)){
transform.position -= transform.forward * speed * Time.deltaTime;
}
because I need the player to move relative to the direction they face. For instance if the player is facing North and presses 'W' (up), they move north. If the player is facing East and presses 'W' (up) they move East.
But I also need this to work with the CharacterController, so need to convert to a Vector 3 ('moveDirection').
characterController.Move(moveDirection * Time.deltaTime);
Thoughts?
is the same vectorial space you dont need to convert to any other space, transform.forward are on global (or world) space so;
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.W)){
moveDirection = transform.forward * speed;
}
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.S)){
moveDirection = transform.forward * speed;
}
characterController.$$anonymous$$ove(moveDirection * Time.deltaTime);
should work.
to clarify what I think you're missing, note the absence of +=
this add the direction vector to the current point, you just need the direction so its just =
Answer by Hellium · Aug 25, 2019 at 01:12 PM
As indicated by DCordoba, transform.forward
is already a vector defined in the World space.
What you really need is the vector expressed in the local space. In your case:
Vector3 moveDirection;
if(Input.GetKey(KeyCode.W)){
moveDirection = Vector3.forward;
}
if(Input.GetKey(KeyCode.S)){
moveDirection = -Vector3.forward;
}
characterController.Move(moveDirection * speed * Time.deltaTime);
Whilst I agree this is the best way to do this. i.e. just move the player up, down, left and right with w, s, a and d respectively and then just change the players orientation.
I am not sure just your code example fully answers the question. Which was albeit a little vague.
To expound on that. They asked how to have W always be the button used to move forward in multiple directions.
The CharacterController
already takes care of the orientation of the object when moving it. So you just need to provide a local direction, and the $$anonymous$$ove
will move the object according to the rotation of the object (the same way transform.Translate
does)
Answer by sacredgeometry · Aug 25, 2019 at 12:41 PM
What you need to be doing is rotating the player and then forward will always be forward.