使用鼠标拖动为相机创建边界
Posted
技术标签:
【中文标题】使用鼠标拖动为相机创建边界【英文标题】:Creating boundaries for Camera with with mouse drag 【发布时间】:2022-01-20 14:31:12 【问题描述】:我制作了一个通过拖动鼠标移动的正交相机,但不知道如何为其创建边界。看来我必须使用 Mathf.Clamp 但不知道如何使用。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamController : MonoBehaviour
public Transform cameraTransform;
public float movementSpeed;
public float movementTime;
public Vector3 newPosition;
public Vector3 dragStartPosition;
public Vector3 dragCurrentPosition;
public Camera cam;
public float maxZoom = 5;
public float minZoom = 20;
public float sensitivity = 1;
public float speed = 30;
float targetZoom;
public float minX = 100;
public float maxX = 120;
// Start is called before the first frame update
void Start()
newPosition = transform.position;
// Update is called once per frame
void Update()
HandleMouseInput();
HandleMovementInput();
targetZoom -= Input.mouseScrollDelta.y * sensitivity;
targetZoom = Mathf.Clamp(targetZoom, maxZoom, minZoom);
float newSize = Mathf.MoveTowards(cam.orthographicSize, targetZoom, speed * Time.deltaTime);
cam.orthographicSize = newSize;
void HandleMouseInput()
if (Input.GetMouseButtonDown(0))
Plane plane = new Plane(Vector3.up, Vector3.zero);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float entry;
if (plane.Raycast(ray, out entry))
dragStartPosition = ray.GetPoint(entry);
if (Input.GetMouseButton(0))
Plane plane = new Plane(Vector3.up, Vector3.zero);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float entry;
if (plane.Raycast(ray, out entry))
dragCurrentPosition = ray.GetPoint(entry);
newPosition = transform.position + dragStartPosition - dragCurrentPosition;
newPosition = Mathf.Clamp(minX, minX);
void HandleMovementInput()
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
newPosition += (transform.forward * movementSpeed);
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
newPosition += (transform.forward * -movementSpeed);
if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
newPosition += (transform.right * movementSpeed);
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
newPosition += (transform.right * -movementSpeed);
transform.position = Vector3.Lerp(transform.position, newPosition, Time.deltaTime * movementTime);
【问题讨论】:
您共享了很多代码,但有什么方法可以将其简化为minimal reproducible example?问题到底出在哪里——是在Update()
中吗?如果是这样,您当前的实施做错了什么?您分享的当前卡在哪里的越多,我们就越有可能帮助您解决问题。请参阅:How to Ask。
感谢您的回复。问题在于无效的 HandleMouseInput。我用过 newPosition = Mathf.Clamp(minX, minX);创建了两个浮动公共浮动 minX 和 max。鼠标拖动停止工作
【参考方案1】:
newPosition = Mathf.Clamp(minX, minX);
你不能只用两个参数来钳位..你需要一个电流、一个最小值和一个最大值..你不能只是将float
转换为Mathf.Clamp
返回的Vector3
(3 个浮点数)
我认为你的意思有点像例如
newPosition.x = Mathf.Clamp(newPosition.x, minX, maxX);
但是,在 HandleMovementInput
之后,您仍然会覆盖它,因此您可能希望更改夹紧的时刻,而是在应用新位置之前立即执行。
【讨论】:
以上是关于使用鼠标拖动为相机创建边界的主要内容,如果未能解决你的问题,请参考以下文章