forked from zxl/LaboratoryProtection
100 lines
2.9 KiB
C#
100 lines
2.9 KiB
C#
using UnityEngine;
|
|
|
|
|
|
public class ObjectCameraRotate : MonoBehaviour
|
|
{
|
|
public bool isAllowInput = true;
|
|
public Transform objecctTarget;
|
|
public Camera mainCamera;
|
|
|
|
public float distance = 7.0f;
|
|
private float eulerAngles_x;
|
|
private float eulerAngles_y;
|
|
public float distanceMax = 10;
|
|
public float distanceMin = 3;
|
|
public float xSpeed = 2;
|
|
public float ySpeed = 2;
|
|
public int yMaxLimit = 360;
|
|
public int yMinLimit = -360;
|
|
public float mouseScrollWheelSensitivity = 1.0f;
|
|
public LayerMask CollisionLayerMask;
|
|
|
|
|
|
private Vector2 mousePosition;
|
|
private Transform child;
|
|
|
|
void Start()
|
|
{
|
|
child = mainCamera.transform;
|
|
var eulerAngles = this.transform.eulerAngles;
|
|
this.eulerAngles_x = eulerAngles.y;
|
|
this.eulerAngles_y = eulerAngles.x;
|
|
}
|
|
void Update()
|
|
{
|
|
if (this.isAllowInput != true)
|
|
return;
|
|
if (Input.GetKeyDown(KeyCode.Mouse1))
|
|
{
|
|
mousePosition = Input.mousePosition;
|
|
}
|
|
else if (Input.GetKey(KeyCode.Mouse1))
|
|
{
|
|
this.eulerAngles_x += (Input.mousePosition.x - mousePosition.x) * Time.deltaTime * this.xSpeed;
|
|
this.eulerAngles_y -= (Input.mousePosition.y - mousePosition.y) * Time.deltaTime * this.ySpeed;
|
|
this.eulerAngles_y = ClampAngle(this.eulerAngles_y, this.yMinLimit, this.yMaxLimit);
|
|
mousePosition = Input.mousePosition;
|
|
}
|
|
|
|
if (Input.GetMouseButton(1))
|
|
{
|
|
var yRot = Input.GetAxis("Mouse X") * xSpeed * Time.deltaTime;
|
|
var xRot = Input.GetAxis("Mouse Y") * ySpeed * Time.deltaTime;
|
|
|
|
transform.Rotate(new Vector3(xRot, -yRot, 0));
|
|
}
|
|
|
|
|
|
var mouseScrollWheel = Input.GetAxis("Mouse ScrollWheel");
|
|
this.distance = Mathf.Clamp(this.distance - (mouseScrollWheel * mouseScrollWheelSensitivity), this.distanceMin, this.distanceMax);
|
|
|
|
child.localPosition = Vector3.forward * GetDistance(child.localPosition.z + mouseScrollWheel * mouseScrollWheelSensitivity);
|
|
if (Physics.Linecast(this.objecctTarget.position, this.child.position, out var hitInfo, this.CollisionLayerMask))
|
|
{
|
|
this.distance = hitInfo.distance - 0.05f;
|
|
}
|
|
}
|
|
|
|
public float GetDistance(float value)
|
|
{
|
|
if (-value < distanceMin)
|
|
{
|
|
return -distanceMin;
|
|
}
|
|
if (-value > distanceMax)
|
|
{
|
|
return -distanceMax;
|
|
}
|
|
return value;
|
|
}
|
|
public float ClampAngle(float angle, float min, float max)
|
|
{
|
|
while (angle < -360)
|
|
{
|
|
angle += 360;
|
|
}
|
|
while (angle > 360)
|
|
{
|
|
angle -= 360;
|
|
}
|
|
return Mathf.Clamp(angle, min, max);
|
|
}
|
|
|
|
public void ResetDistance()
|
|
{
|
|
if (child != null)
|
|
{
|
|
child.localPosition = Vector3.forward * -distanceMax;
|
|
}
|
|
}
|
|
} |