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的...我想使用鼠标拖动任何3D对象(立方体,球体等)...我从层次结构中创建对象,并将脚本应用于要拖动的对象。 ....当我运行该对象时,未选中该对象且未将其拖动...........我检查了许多站点,但未找到任何合理的解决方案。
答案 0 :(得分:0)
如果我对问题的理解正确,Unity的IDragHandler可以解决您的问题。
此接口可用于接收DragEvent。为此,您必须在类中实现方法void OnDrag (PointerEventData data)
。要响应OnDrag事件的开始,可以使用void OnBeginDrag(PointerEventData eventData)
方法实现IDragStart接口。最后,您还可以使用IDragEnd接口和方法void OnEndDrag(PointerEventData eventDat)
。
有关IDragHandler的确切用法,请参见Unity文档。这是链接:
IDragHandler interface in UnityEngine.EventSystems
希望能对您有所帮助。