- Home /
Dragging camera around object using mouse issue
Hello there, As I'm new to Unity (that's my excuse), the answer to this may well be rather obvious. I've attached a script to a main camera which has been parented to a movable object, in this case a character. When you hold down the right mouse button and drag, the camera will move around the player. The main problem I seem to be having is that after a while, the camera slowly moves away from the object, eventually zooming way out of the map. Clearly I've done something incorrect, I'll pop the code below:
var target:Transform; var camRotationSpeed:float;
// Velocity & smoothing of dragCam. var smoothTime = 0.3; private var velocity = Vector3.zero;
// Camera default location var camZoom:float; // Distance (uses Z axis) var camXpos:float; // Horizontal Position var camYpos:float; // Vertical Position
function Start(){ Debug.Log("Game Camera Script Loaded OK."); }
function Update(){ transform.LookAt(target); if(Input.GetButton("Grabbed")){ // Check if right mouse button is down grabLook = true;
var targetPositionInit:Vector3 = transform.TransformPoint(Vector3(Input.GetAxis("Mouse X") camRotationSpeed, Input.GetAxis("Mouse Y") camRotationSpeed, 0)); transform.position = Vector3.SmoothDamp(transform.position, targetPositionInit, velocity, smoothTime);
// Check that camera hasn't gone too high.
var zTrack:float = transform.position.z;
var yTrack:float = transform.position.y;
Debug.Log(zTrack);
if(yTrack > 4){
Debug.Log("Vertical Target Reached");
}
else if(yTrack < -4){
Debug.Log("Negative Vertical Target Reached");
}
else{
Debug.Log("In Safe Zone");
}
}
else{ // Snap camera position back into place after release
grabLook = false;
var targetPositionReturn:Vector3 = target.TransformPoint(Vector3(camXpos, camYpos, camZoom));
transform.position = Vector3.SmoothDamp(transform.position, targetPositionReturn, velocity, smoothTime);
}
}