unity 鼠标拖拽物体(一)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class RayButton : MonoBehaviour
{


    private Camera cam;//发射射线的摄像机
    private GameObject go;//射线碰撞的物体
    private string btnName;//射线碰撞物体的名字
    private Vector3 screenSpace;
    private Vector3 offset;
    private GameObject chai;//整体


    void Start()
    {
        chai = GameObject.Find("tzmx");
        cam = Camera.main;
    }




    void Update()
    {
        //整体初始位置
        chai.transform.position = new Vector3(0, 0, 0);
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        //从摄像机发出到点击坐标的射线
        RaycastHit hitInfo;


        if (Physics.Raycast(ray, out hitInfo))
        {
            //划出射线,只有在scene视图中才能看到
            Debug.DrawLine(ray.origin, hitInfo.point);
            go = hitInfo.collider.gameObject;
            btnName = go.name;
            print(btnName);
            screenSpace = cam.WorldToScreenPoint(go.transform.position);
            offset = go.transform.position - cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
        }
        if (Input.GetMouseButton(0))
        {


            if (Input.GetAxis("Mouse X") != 0 || Input.GetAxis("Mouse Y") != 0)
            {
                Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
                Vector3 currentPosition = cam.ScreenToWorldPoint(currentScreenSpace) + offset;
                go.transform.position = currentPosition;
            }


        }


    }






}

你可能感兴趣的:(unity 鼠标拖拽物体(一))