3d物体移动
- 创建一个cube,并挂上一个脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragCube : MonoBehaviour {
Vector3 oldMouse;
Vector3 oldCube;
bool isHit = false;
GameObject cube;
void Start () {
}
void Update () {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray,out hit))
{
if (Input.GetMouseButtonDown(0)&&hit.collider.name.Contains("Cube") )
{
isHit = true;
cube = hit.collider.gameObject;
oldMouse = Input.mousePosition;
oldCube = Camera.main.WorldToScreenPoint(hit.collider.transform.position);
}
}
if (Input.GetMouseButtonUp(0))
{
isHit = false;
}
if (isHit)
{
Vector3 offset = Input.mousePosition - oldMouse;
Vector3 cubeOffset = oldCube + offset;
cube.transform.position = Camera.main.ScreenToWorldPoint(cubeOffset);
}
}
}
- 运行后可以抓取cube移动,只是平面移动,不会改变z的值
Ui移动
- 创建image,使用射线接口拖动UI
- 脚本必须挂在要拖动的物体身上,
- 射线接口是在EventSystems命名空间下
- 接口是IDragHandler,进行拖拽
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class ImageDrag : MonoBehaviour, IDragHandler
{
public void OnDrag(PointerEventData eventData)
{
GameObject image= eventData.pointerDrag;
image.transform.position = Input.mousePosition;
}
}