首页 > 代码库 > 关于Unity3D中鼠标移动指定物体的解决方案

关于Unity3D中鼠标移动指定物体的解决方案

一、鼠标拾取物体的原理

在Unity3D当中,想要在观察面(Aspect)中拾取物体(有碰撞属性)的方法一般如下:

1、声明一个观察的摄像机、一个从摄像机原点出发的射线Ray以及一个用于检测碰撞的RaycastHit;

2、将射线Ray定义为从摄像机原点出发并且指向当前鼠标所在的坐标(屏幕坐标);

3、定义碰撞RaycastHit为射线Ray与有碰撞属性的物体的碰撞点。

具体代码实现如下(C#代码):

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

public class camera : MonoBehaviour
{
    public Camera ca;
    private Ray ra;
    private RaycastHit hit;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
            ra = ca.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ra, out hit))
            {  
                     
            }
    }
}

 

应用一:当鼠标按住不动时,移动被选定物体随鼠标一起移动

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

public class camera : MonoBehaviour
{
    public Camera ca;
    private Ray ra;
    private RaycastHit hit;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            ra = ca.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ra, out hit))
            {
                hit.collider.gameObject.transform.position = ca.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, hit.collider.gameObject.transform.position.z));
            }
        }
    }
}

 

应用二:当鼠标点击物体时,物体随鼠标一起移动;当鼠标再次点击时,放下物体。

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

public class camera : MonoBehaviour {
    public Camera ca;
    private Ray ra;
    private RaycastHit hit;
    private int flag = 0;

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            ra = ca.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ra, out hit))
            {
               if (flag == 0)
                {
                    flag = 1;
                } else
                {
                    flag = 0;
                }
            }
        }
        if (flag == 1)
        {
            hit.collider.gameObject.transform.position = ca.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, hit.collider.gameObject.transform.position.z));
        }

    }
}

 出自http://blog.csdn.net/sysujackjiao/article/details/69396274

关于Unity3D中鼠标移动指定物体的解决方案