unity实现鼠标点击后拖拽物体

我们经常要在unity中实现,鼠标点击物体后,选中物体。然后物体跟随鼠标,直到拖拽到指定物体位置,也就是吸附到指定物体上去。

(1)此案例中有两个物体。

(2)tougu001和tougu002,附加的代码分别是 BLtougu001和BLTriggerTouGu002

(3)tougu001 Inspector面板如下:

unity实现鼠标点击后拖拽物体_第1张图片


(4)tougu002 Inspector面板如下:

unity实现鼠标点击后拖拽物体_第2张图片


(5)tougu001 代码

using UnityEngine;
using System.Collections;

public class BLtougu001 : MonoBehaviour {
    public BLTriggerTouGu002 m_BLTriggerTouGu002;

    public float mousestate = 0f;

    public Vector3 V3;

    public Camera cam;

    RaycastHit hit;
    // Use this for initialization
    void Start () {
        V3 = transform.position;
        cam = GameObject.Find("Main Camera").GetComponent();
    }
 
 // Update is called once per frame
 void Update () {
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit) && Input.GetMouseButtonDown(0)&&hit.transform.gameObject.name == "tougu001")
        {
                mousestate = 1;
        }


        else if (Input.GetMouseButtonUp(0) && m_BLTriggerTouGu002.tougustate == 0)
        {
            mousestate = 0;
            transform.position = V3;

        }
        else if (Input.GetMouseButtonUp(0)&& m_BLTriggerTouGu002.tougustate==1)
        {
            mousestate = 0;

        }


        if (mousestate == 1&& m_BLTriggerTouGu002.tougustate!=2)
        {
            Vector3 Pos = Camera.main.WorldToScreenPoint(transform.position);
            Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Pos.z);
            transform.position = Camera.main.ScreenToWorldPoint(mousePos);


        }

    }
}




(6)tougu002 代码


using UnityEngine;
using System.Collections;

public class BLTriggerTouGu002 : MonoBehaviour {
    public BLtougu001 m_BLtougu001;
    public GameObject tougu;
    public float tougustate = 0f;
    private AudioSource audio_BLTriggerTouGu002;

    // Use this for initialization
    void Start () {
        tougu = GameObject.Find("tougu001");
        audio_BLTriggerTouGu002 = GetComponent();
    }
 
 // Update is called once per frame

        void OnTriggerStay(Collider col)

        {
             if(tougustate!=2)
              tougustate = 1;
            if (col.tag == "touGu" && m_BLtougu001.mousestate == 0 && tougustate==1)
            {
        
              tougu.transform.position = transform.position;
                 tougustate = 2;
                transform.parent.SendMessage("CountBone", true);
            audio_BLTriggerTouGu002.Play();
            }
        }

    void OnTriggerExit(Collider col)

    {
        if (tougustate != 2)
        {
            tougustate = 0;
        }
    }

}







你可能感兴趣的:(unity)