分享:Unity3D模型跟随鼠标移动功能的小脚本 (屏幕坐标和三维空间坐标转换)

技术分享
using UnityEngine;
using System.Collections;

public class ModelsPosChange : MonoBehaviour {
    RaycastHit hit;
    private Transform Icon;
    bool isMove = false;
    void FixedUpdate() {
        if (isMove) {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if ((Physics.Raycast(ray, out hit,500)) && (null != hit.collider)) {
                Debug.DrawLine(ray.origin, hit.point);
                Icon = transform.GetComponent<Transform>();
                Vector3 screenPos = Camera.main.WorldToScreenPoint(Icon.position);
                Vector3 offset = Icon.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPos.z));
                Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPos.z);
                Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
                Icon.position = worldPos;
            }
            transform.renderer.material.color = Color.green;
            if (Input.GetKey(KeyCode.Delete)) {
                Destroy(this.gameObject);
            }

        } else {
            transform.renderer.material.color = Color.white;
        }
    }
    void OnMouseDown() {
        isMove = !isMove;
        
    }
}
View Code

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。