分享: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; } }