transform.forward giving unwanted movement
Hi all,
I'm working on a Virtual Reality project with the oculus where the player should simply move through the environment and can look around and interact with some objects.
How this, the movement in this case, will work is that the player will press a button (for now that's "W") and then move in the direction the player is looking. I got that to work, sort of, with the following code (note: that I as well partially found on the internet):
public float moveSpeed = 2f;
void Update () {
if (Input.GetKey (KeyCode.W))
{
transform.position += Camera.main.transform.forward * Time.deltaTime * moveSpeed;
}
}
Problem with this code is that the player can move into the air or through the ground as the .forward, z axis, rotates with the direction the camera is facing. How can I only use the Y axis rotation of the camera so that the transform .forward will never point towards the ground or into the air?
Or are there other, more efficient, ways that I should know of? I tried looking it up, but didn't find any solutions that worked for me so far.
Any advice would be highly appreciated.
No idea if it works but try to toggle the Global/Local option which's right above the animation button above the Scene screen or right below the window tab.
Answer by Dave-Carlile · Oct 12, 2015 at 07:58 PM
You can just zero out the forward vector component that you want to ignore. If you're moving on the x/z plane then you can zero out y, so the movement can't happen in the y direction at all...
Vector3 forward = Camera.main.transform.forward;
forward.y = 0; // zero out y, leaving only x & z
transform.position += forward * Time.deltaTime * moveSpeed;
Wow thank you so much for your extremely fast reply and also the perfect solution to my problem. Now that I see it I can't believe I thought of it myself! :) And like you said, if the player will not move on the Y axis it can just be zero'd out. So lets hope my colleagues don't change their $$anonymous$$ds now.
Once again thanks a lot for your time and help!
Your answer
Follow this Question
Related Questions
Make the camera follow the highest player up but not down. 0 Answers
How to Move the Object According to Image tracking 0 Answers
How to make a NavMeshAgent move in the direction it is looking? 4 Answers
Any scrips that is like WOW or GW2 movement? 0 Answers
I have a little issue with top down movement using the camera orientation. 0 Answers