I’m new and don’t really know what I’m doing working with rotations and the camera. I found a script in a free asset that almost does what I want and I started modifying it. The code below is what I have right now.
I’m trying to get the camera to zoom in and out from the player with the scroll wheel, rotate around the player and up and down by holding down the right mouse button and moving the mouse, and then trying to get the camera to stay locked in place relative to the player when you are not moving the camera IE you have the camera on your right side and turn while running and its still on your right side.
This script works exactly like I want it to now except for one major glitch. If I turn the player at all and then go to move the camera again it will jump to a new position at the first click of the mouse. After that it works just how I want it too until I turn the player again. I’m hoping someone knows an easy way to fix this.
Edit: the camera is a child of the player object and the script is attached to it.
public class ThirdPersonCamera : MonoBehaviour
{
private const float Y_ANGLE_MIN = 0.0f;
private const float Y_ANGLE_MAX = 80.0f;
public Transform lookAt; //this is set in inspecter to the characters head.
public Transform camTransform;
public float distance = 5.0f; //how far away the camara is
private float currentX = 0.0f;
private float currentY = 45.0f;
private float speed = 3f; //speed multiplier for moving camera.
Quaternion rotation;
private void Start()
{
camTransform = transform;
rotation = Quaternion.Euler(currentY, currentX, 0); //get camera in the starting position.
camTransform.position = lookAt.position + rotation * new Vector3(0, 0, -distance);
}
private void Update()
{
distance -= Input.mouseScrollDelta.y * 40 * Time.deltaTime; // mouse scroll to change cameras distance from player.
distance = Mathf.Clamp(distance, 0.7f, 10f); //stop camera from going into player or way far away.
if (Input.GetMouseButton(1)) //try to get the camera to only move while holding down right mouse button.
{
currentX += Input.GetAxis("Mouse X") * speed;
currentY -= Input.GetAxis("Mouse Y") *speed; //- so camera goes the other way
currentY = Mathf.Clamp(currentY, Y_ANGLE_MIN, Y_ANGLE_MAX);
}
}
private void LateUpdate()
{
Vector3 dir = new Vector3(0, 0, -distance);
if (Input.GetMouseButton(1) || Input.mouseScrollDelta.y != 0) //trying to keep the camera locked in place relative to the player when not moving the camera.
{
rotation = Quaternion.Euler(currentY, currentX, 0);
camTransform.position = lookAt.position + rotation * dir;
}
camTransform.LookAt(lookAt.position);
}
}
Yes, you're right. Doesn't work at all. But there is a lot more to it, i think. What happens, or shall hapen if you release the RMB? Shall the camera snap back in its original position behind the player or shall the player change the walk direction?
– CybexGS