简体   繁体   English

Unity3D C#在旋转后计算正确的前进

[英]Unity3D C# calculate correct forward after rotation

I'm starting my development using Unity. 我正在使用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. 所以我旋转,我可以移动,但它只是在Z线移动,我知道我正在调用Z特定的运动。 But with Javascript i can do something 但使用Javascript我可以做点什么

     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的用法。 transform.forward is just a vector to tell you what direction your gameObject faces, it depends on transform.rotation. transform.forward只是一个向量来告诉你gameObject面向的方向,它取决于transform.rotation。

If you want to move your GameObject, always use transform.position : 如果要移动GameObject,请始终使用transform.position

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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