Hi all,
I am writing a camera movement script, but I cant get it to work properly. The camera is slight rotated on the X-axis and when I move the camera on the x axis the script works fine. However, when I want to move it only on the Y or Z axis, the camera moves on both the X and Y axis, creating an unwanted zoom effect. I somehow need to account for the camera rotation when translating the position, but I don’ know how. Can anyone lend me a hand?
private var speed = 150.0f;
private var turnSpeed = 35.0f;
private var turnSpeedMouse = 10.0f;
function Update ()
{
var movement = Vector3.zero;
//forward
if(Input.GetKey("w"))
{
movement.y++;
}
//backward
if(Input.GetKey("s"))
{
movement.y--;
}
//left
if(Input.GetKey("a"))
{
movement.x--;
}
//right
if(Input.GetKey("d"))
{
movement.x++;
}
//turn right
if(Input.GetKey("e"))
{
transform.Rotate(Vector3.up, Time.deltaTime * turnSpeed, Space.World);
}
//turn left
if(Input.GetKey("q"))
{
transform.Rotate(0, -1 *Time.deltaTime * turnSpeed, 0, Space.World);
}
//this bit of code I found on the forums, but it does not work well.
var theta : float = transform.rotation.y;
var phi : float = transform.rotation.x;
var xMove : float = movement.x * Mathf.Sin(phi) * Mathf.Cos(theta);
var yMove : float = movement.y * Mathf.Sin(phi) * Mathf.Cos(theta);
var zMove : float = movement.z * Mathf.Cos(phi);
var xxxx : Vector3 = Vector3(xMove,yMove,zMove);
transform.Translate(xxxx * speed * Time.deltaTime, Space.Self);
}