- Home /
Player movement and trigonometry help, anyone
Here's my code for the camera (player) moving forward when "W" is pressed, and rotating right when the Right arrow key is pressed in a 3D game:
if(Input.GetKeyDown(KeyCode.W)){
print ("W");
transform.Translate(Mathf.Cos(rotation),0,Mathf.Sin(rotation));
}
if(Input.GetKeyDown(KeyCode.RightArrow)){
print ("Right");
rotation += 1;
transform.Rotate(0,1,0);
}
So far rotating the camera works fine, but when moving forward with "W" it seems to move at the wrong angle, I'm guessing this is a problem with my math, but what's the problem? Both pieces of code are within "Update".
Answer by Owen-Reynolds · Feb 13, 2013 at 09:29 PM
Mixing radians and degrees. Built-in Unity functions, such as transform.Rotate, use degrees. But real math functions, such as cosine, expect input in radians.
So, maybe keep rotation
as degrees, but convert to rads for Cos/Sin: Math.Cos(rotation * Mathf.Deg2Rad);
(deg2Rad is just 2PI/360)
But transform.forward
, mentioned in the previous reply, is better (as long as the camera isn't tilted, since forward will gladly move you up if you face up-ish.)
Answer by Dave-Carlile · Feb 13, 2013 at 08:32 PM
You don't need to do that sort of math. The transform.forward
vector points in the direction the object is facing. You just need to update the position, taking that direction into account...
transform.position += transform.forward * speed * Time.deltaTime;
speed
is a constant or variable that contains the movement speed in units per second.
Time.deltaTime
scales the movement speed by the frame draw time, so it will always move the same speed regardless of the frame rate.