Problems with rotation after zoom (camera like Sketchfab)
I would like to have a camera like Sketchfab (rotate by dragging and moving; zoom to mouse pointer location) My problem that after zooming to mouse pointer I'd like to rotate around new location (mouse position to which I zoomed), but actually zoom is set to default target and it rotates around it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraRotate : MonoBehaviour
{
public Transform target;
public Vector3 targetOffset;
public float distance = 5.0f;
public float maxDistance = 20;
public float minDistance = .6f;
public float xSpeed = 200.0f;
public float ySpeed = 200.0f;
public int yMinLimit = -80;
public int yMaxLimit = 80;
public int zoomRate = 40;
public float panSpeed = 0.3f;
public float zoomDampening = 5.0f;
private float xDeg = 0.0f;
private float yDeg = 0.0f;
private float currentDistance;
private float desiredDistance;
private Quaternion currentRotation;
private Quaternion desiredRotation;
private Quaternion rotation;
private Vector3 position;
void Start() { Init(); }
void OnEnable() { Init(); }
public void Init()
{
if (!target)
{
GameObject go = new GameObject("Cam Target");
go.transform.position = transform.position + (transform.forward * distance);
target = go.transform;
}
distance = Vector3.Distance(transform.position, target.position);
currentDistance = distance;
desiredDistance = distance;
position = transform.position;
rotation = transform.rotation;
currentRotation = transform.rotation;
desiredRotation = transform.rotation;
xDeg = Vector3.Angle(Vector3.right, transform.right);
yDeg = Vector3.Angle(Vector3.up, transform.up);
}
void LateUpdate()
{
if (Input.GetMouseButton(0))
{
xDeg += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
yDeg -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
yDeg = ClampAngle(yDeg, yMinLimit, yMaxLimit);
desiredRotation = Quaternion.Euler(yDeg, xDeg, 0);
currentRotation = transform.rotation;
rotation = Quaternion.Lerp(currentRotation, desiredRotation, Time.deltaTime * zoomDampening);
transform.rotation = rotation;
position = target.position - (rotation * Vector3.forward * desiredDistance + targetOffset);
transform.position = position;
}
else if (Input.GetAxis("Mouse ScrollWheel") != 0)
{
RaycastHit hit;
Ray ray = this.transform.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
Vector3 desiredPosition;
if (Physics.Raycast(ray, out hit))
{
desiredPosition = hit.point;
}
else
{
desiredPosition = transform.position;
}
float distance0 = Vector3.Distance(desiredPosition, transform.position);
Vector3 direction = Vector3.Normalize(desiredPosition - transform.position) * (distance0 * Input.GetAxis("Mouse ScrollWheel"));
transform.position += direction;
}
}
private static float ClampAngle(float angle, float min, float max)
{
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp(angle, min, max);
}
}
Comment