代码是用C#编写的,我想用鼠标在unity 3D中拖动任何对象.我尝试了很多方法,但没有找到任何合理的解决方案


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Drag: MonoBehaviour
{
GameObject getTarget;
bool isMouseDragging;
Vector3 offsetValue;
Vector3 positionOfScreen;
void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hitInfo;
getTarget = ReturnClickedObject(out hitInfo);
if (getTarget != null)
{
isMouseDragging = true;
//Converting world position to screen position.
positionOfScreen = Camera.main.WorldToScreenPoint 
(getTarget.transform.position);
offsetValue = getTarget.transform.position - Camera.main.Screen 
ToWorldPoint(new Vector3(Input.mousePosition.x,   
Input.mousePosition.y, positionOfScreen.z));
}
}
if (Input.GetMouseButtonUp(0))
{
isMouseDragging = false;
}
if (isMouseDragging)
{
Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x Input.mousePosition.y, positionOfScreen.z);
Vector3 currentPosition = Camera.main.ScreenToWorldPoint (currentScreenSpace) + offsetValue;
getTarget.transform.position = currentPosition;
}
}
GameObject ReturnClickedObject(out RaycastHit hit)
{
GameObject target = null;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray.origin, ray.direction * 10, out hit))
{
target = hit.collider.gameObject;
}
return target;
}
}

代码是关于统一三维。。。我想用鼠标拖动任何3D对象(立方体、球体等(。。。我从层次结构创建对象,并将脚本应用到我想要拖动的对象上。。。。。当我运行时,对象没有被选中,也没有被拖动。。。。。。。。。。。我检查了很多网站,但没有找到任何合理的解决方案。

如果我正确理解了这个问题,unity的IDragHandler可以解决你的问题。

此接口可用于接收DragEvent。为此,您必须在类中实现方法void OnDrag (PointerEventData data)。要响应OnDrag事件的启动,可以使用voidOnBeginDrag(PointerEventData eventData)方法实现IDragStart接口。最后,您还可以使用IDragEnd接口和方法void OnEndDrag(PointerEventData eventDat)进行反应。

有关IDragHandler的确切用法,您可以查看Unity文档。这是链接:

UnityEngine中的IDragHandler接口。EventSystems

我希望这能帮助你。

相关内容

最新更新