Unity3D拖動任意對象GameObject移動到任意地方

來源:互聯網
上載者:User

標籤:gameobject拖拽

今天不是很忙,研究了一下拖拽GameObject移動到任意位置,沿x軸和z軸移動,其他的也就不說了,上代碼:

using UnityEngine;using System.Collections;public class DragAndDrog : MonoBehaviour {    private GameObject target;    private bool isMouseDrag;    private Vector3 screenPosition;    private Vector3 offset;// Use this for initializationvoid Start () {}// Update is called once per framevoid Update () {        GameObjectDragAndDrog();}    //任意拖拽    private GameObject ReturnGameObjectDrag(out RaycastHit hit)    {        target = null;        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);        if (Physics.Raycast(ray.origin, ray.direction * 10, out hit))        {            target = hit.collider.gameObject;        }        return target;    }    //拖拽Updata    private void GameObjectDragAndDrog()    {        if (Input.GetMouseButtonDown (0))        {            RaycastHit hitInfo;            target = ReturnGameObjectDrag(out hitInfo);            if (target != null)            {                isMouseDrag = true;                screenPosition = Camera.main.WorldToScreenPoint(target.transform.position);                offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));            }              }        if (Input.GetMouseButtonUp(0))        {            isMouseDrag = false;        }        if (isMouseDrag)        {            Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);            Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset;            target.transform.localPosition = new Vector3(currentPosition.x, currentPosition.y, currentPosition.z);        }    }}本指令碼可以載入任意一個對象GameObject,情境中所有帶Collider的對象,當滑鼠點擊拖動時候都可以沿x和z軸拖動。之前,都是要拖動那個GameObject就會寫一個指令碼掛在上面,今天實現了不用每一個要拖動的GameObject都掛載指令碼,也不用將移動的GameObject賦給某個變數。


本文出自 “Unity_3D技術探討” 部落格,請務必保留此出處http://caoliyong.blog.51cto.com/9944020/1740192

Unity3D拖動任意對象GameObject移動到任意地方

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.