Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity3D C# calculate correct forward after rotation

Tags:

c#

unity3d

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.

like image 870
Lefsler Avatar asked Mar 10 '12 00:03

Lefsler


People also ask

Can I use C for Unity?

The language that's used in Unity is called C# (pronounced C-sharp). All the languages that Unity operates with are object-oriented scripting languages. Like any language, scripting languages have syntax, or parts of speech, and the primary parts are called variables, functions, and classes.

Do you need C# for Unity?

According to its official documentation, C# is the only language that Unity supports natively. For anyone just starting out with Unity, or anyone with previous knowledge of object-oriented programming, C# is the best Unity programming language to begin with.

Is Unity in C++ or C#?

Both Unity and UnrealEngine utilize C++ in their source code: Unity is partially written using C++ and C#, whereas Unreal Engine is written in C++ entirely. C++ is widely used to develop high-tier game engines and critical service applications where optimal resource utilization and performance are a priority.


1 Answers

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;
like image 131
Chchwy Avatar answered Nov 01 '22 00:11

Chchwy