Anonymous
Anonymous

Reputation: 53

Unity3d, 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;
}
  1. Is there any dependency on Time.deltaTime?

Upvotes: 0

Views: 484

Answers (1)

Chuck
Chuck

Reputation: 2102

You're setting the velocity, so if you mean speed when you use speed then there shouldn't be any need to include Time.deltaTime.

As far as performance goes, (1) you can implement it both ways and profile to find out which takes longer, and (2) the difference is almost certainly negligible and you should go with whatever is easier to read, because readability is key to maintainability.

Regarding point 2, IMO neither option is readable. Are you just trying to make the thing move in its local forward direction? Try using the TransformDirection method, like:

PlayerRigidbody.velocity = speed*transform.TransformDirection(Vector3.forward);

transform.TransformDirection says,

Description

Transforms direction from local space to world space.

so just pass that function the Vector3.forward and let Unity's built-in method handle the math.

Upvotes: 1

Related Questions