Unity3D C # calculates the correct forward direction after rotation

I am starting my development with Unity. I am doing something like this:

if(Input.GetKey(KeyCode.A))newValues[1]-=this.turnSpeed*(float)Time.deltaTime; if(Input.GetKey(KeyCode.D))newValues[1]+=this.turnSpeed*(float)Time.deltaTime; transform.Rotate(0, newValues[1], 0); if(Input.GetKey(KeyCode.W))newValues[0]+=this.speed*transform.forward.z*(float)Time.deltaTime; if(Input.GetKey(KeyCode.S))newValues[0]-=this.speed*transform.forward.z*(float)Time.deltaTime; transform.position = new Vector3(transform.position.x, transform.position.y, (float)newValues[0]); 

So, I spin, and I can move, but it only moves in line Z, I know that I am causing a Z-specific movement. But with Javascript I can do something

  transform.forward+=this.speed*transform.forward*(float)Time.deltaTime; 

Therefore, I do not need to make a new vector process and copy it into a separate variable, and it works like a charm, using rotation and using it as an orientation for myself when it turns.

+6
source share
1 answer

You may misunderstand the use of transform.forward. transform.forward is just a vector that tells you which direction your gameObject is in; it depends on transform.rotation.

If you want to move your GameObject, always use transform.position :

  transform.position += this.speed * transform.forward * (float)Time.deltaTime; 
+7
source

Source: https://habr.com/ru/post/910385/


All Articles