Moving the player forward

Good evening. I am realizing (Unity3d) the moving forward (in the plane which is made by X- and Z-axis) using Rigidbody.velocity, the direction depends on MyPlayer.transform.localEulerAngles.y. Tell me, please:

1.Which of the realizations of the method for the button which moves (it will be called every frame if the button is pressed) is “cheaper”:
a)

public void MoveForward()
{
   PlayerRigidbody.velocity = new Vector3(speed * (float)(Math.Sin(((double)(transform.localEulerAngles.y / 180)) * Math.PI)), PlayerRigidbody.velocity.y, speed * (float)(Math.Cos(((double)(transform.localEulerAngles.y / 180)) * Math.PI)));
}

b)

public void MoveForward()
{
   Quaternion rotation = Quaternion.AngleAxis((transform.localEulerAngles.y - 180), Vector3.up);
   Vector3 temp = new Vector3(0, PlayerRigidbody.velocity.y, -speed);
   PlayerRigidbody.velocity = rotation * temp;
}

2.Is there any dependency on Time.deltaTime?

a) It’s not going to matter unless you have thousands of players. If you really want to know: see what the profiler has to say about it. Generally I’d recommend to go with the code that is easier to read and maintain. After all, you have just one player.

b) It’s up to you. Generally it is advised to multiply final velocity by Time.deltaTime to ensure movement speed does not depend on framerate. However since you’re not using it here you’d have to re-tweak your speed variable.

1 Like

Thank you very much. So, would it be better to write

public void MoveForward()
{
   Quaternion rotation = Quaternion.AngleAxis((transform.localEulerAngles.y - 180), Vector3.up);
   Vector3 temp = new Vector3(0, PlayerRigidbody.velocity.y, -speed);
   PlayerRigidbody.velocity = rotation * temp * Time.deltaTime;
}

?
And will the speed depend on the framerate if I don’t do that?

If you’re doing the velocity integration yourself, then yes. In that case you’ll have something like:

transform.position = transform.position + velocity * Time.deltaTime;

in your Update() function.

If velocity integration is done by the physics engine, like the OP seems to be doing it, then no, just set the velocity in units/s and you’re done.

So whatever this code above does, Time.deltaTime makes absolutely no sense there. Without understanding what you’re actually trying to do, this will probably work:

public void MoveForward()
{
   Quaternion rotation = Quaternion.AngleAxis((transform.localEulerAngles.y - 180), Vector3.up);
   Vector3 temp = new Vector3(0, PlayerRigidbody.velocity.y, -speed);
   PlayerRigidbody.velocity = rotation * temp; // No multiplication with Time.deltaTime or Time.fixedDeltaTime here
}

Since the velocity should be set in every physics frame, MoveForward() should be called from within the FixedUpdate() method.

1 Like

Do you know that you can use transform.forward?

1 Like