Unity 鼠标控制3d物体和UI的抓取移动(笔记)

文章目录


3d物体移动

  1. 创建一个cube,并挂上一个脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragCube : MonoBehaviour {
    
    
    Vector3 oldMouse;
    Vector3 oldCube;
    bool isHit = false;
    GameObject cube;
	// Use this for initialization
	void Start () {
    
    
		
	}
	
	// Update is called once per frame
	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);//屏幕坐标转化成世界坐标
        }
	}
}

  1. 运行后可以抓取cube移动,只是平面移动,不会改变z的值

Ui移动

  1. 创建image,使用射线接口拖动UI
  2. 脚本必须挂在要拖动的物体身上,
  3. 射线接口是在EventSystems命名空间下
  4. 接口是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;
    }
}


猜你喜欢

转载自blog.csdn.net/weixin_44954896/article/details/125020066