简体   繁体   中英

Unity3D C# calculate correct forward after rotation

I'm starting my development using Unity. I'm doing something like that:

    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 rotate and i can move, but it moves just in the Z line, i know i'm calling the Z specific movement. But with Javascript i can do something

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

So i don't need to do the new vector process and copy to a separate variable and it works like a charm, using the rotation and using as orientation to himself when it's rotated.

you may misunderstand the usage of transform.forward. transform.forward is just a vector to tell you what direction your gameObject faces, 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM