我要:
我尝试过但对我不起作用的代码:
void Update()
{
point = Camera.main.ScreenToWorldPoint(
new Vector3(Input.mousePosition.x,
(transform.position.y-Camera.main.transform.position.y),
(transform.position.z-Camera.main.transform.position.z)));
point.y = transform.position.y;
point.z = transform.position.z;
transform.position = point;
}
答案 0 :(得分:0)
要钳位一个值,可以使用Mathf.Clamp()
方法。
完整的解决方案可能看起来像这样:
将脚本添加到杠杆对象:
using UnityEngine;
using UnityEngine.EventSystems;
public class MoveOnMouseDrag : MonoBehaviour {
public float halfDistance;
void Start()
{
EventTrigger trigger = GetComponent<EventTrigger>();
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = EventTriggerType.Drag;
entry.callback.AddListener((data) => { OnDragDelegate((PointerEventData)data); });
trigger.triggers.Add(entry);
}
public void OnDragDelegate(PointerEventData data)
{
float distanceFromCamera = Vector3.Distance(Camera.main.transform.position, transform.position);
var newPos = Camera.main.ScreenToWorldPoint(new Vector3(data.position.x, data.position.y, distanceFromCamera));
transform.position = new Vector3(Mathf.Clamp(newPos.x, -halfDistance, halfDistance),
transform.position.y,
transform.position.z);
}
}
为了使脚本起作用,您必须将EventTrigger
组件添加到同一对象,将EventSystem
添加到场景,将PhysicsRaycaster
组件添加到摄像机。