I’m trying to create an MMO-style camera, i.e. a camera that rotates around an object. When the player holds down the left-mouse, the camera rotates around the object. The right-mouse button does the same thing excepting that the object matches the y-axis rotation of the camera. The camera seems to be rotating properly, but when between certain values, the player object’s rotation (not the camera[I think]) seems to go awry. I’m not sure what the exact numbers are (the seem to very) but it’s always when the camera is facing the same general direction, that is, roughly between the negative x and z axis in world-space.
Here is my code:
#pragma strict
var objectToFollow : GameObject;
var cameraObject : GameObject;
var startingDistance = 0.0;
var startingHeight = 0.0;
var sensitivity = 10;
var playerSpeed = 0.0;
private var distance : float;
private var height : float;
private var rotationVector = Vector3.back;
function Start () {
distance = startingDistance;
height = startingHeight;
cameraObject.transform.position = objectToFollow.transform.position +
(Quaternion.Euler(0,objectToFollow.transform.eulerAngles.y,0) * Vector3.back * distance);
}
function Update () {
//Mouse routines BEGIN
distance = Mathf.Clamp(distance + Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * 200 , 0, 20);
if(Input.GetMouseButton(1))
{
objectToFollow.transform.rotation.y = cameraObject.transform.rotation.y;
}
if(Input.GetMouseButton(0) || Input.GetMouseButton(1))
{
if(Input.GetAxis("Mouse X")!=0)
{
rotationVector = Quaternion.Euler(0,Input.GetAxis("Mouse X") * sensitivity,0) * rotationVector;
}
if(Input.GetAxis("Mouse Y")!=0)
{
rotationVector = Quaternion.AngleAxis(-Input.GetAxis("Mouse Y") * sensitivity,
cameraObject.transform.right) * rotationVector;
}
}
var hit : RaycastHit;
if(Physics.Raycast(objectToFollow.transform.position,rotationVector,hit,distance))
{
cameraObject.transform.position = objectToFollow.transform.position + (rotationVector.normalized * hit.distance);
} else {
cameraObject.transform.position = objectToFollow.transform.position + (rotationVector.normalized * distance);
}
cameraObject.transform.LookAt(objectToFollow.transform);
//Mouse routines END
//Keyboard routines BEGIN
if(Input.GetAxis("Vertical"))
{
objectToFollow.transform.Translate(Vector3.forward * Time.deltaTime * playerSpeed * Input.GetAxis("Vertical"));
}
if(Input.GetAxis("Horizontal"))
{
objectToFollow.transform.Translate(Vector3.right * Time.deltaTime * playerSpeed * Input.GetAxis("Horizontal"));
}
//Keyboard routines END
}