时间:2020-12-13 11:22:16 | 栏目:.NET代码 | 点击:次
本文实例为大家分享了unity3D实现三维物体跟随鼠标的具体代码,供大家参考,具体内容如下
效果图:
1.创建一个三维物体Cylinder圆柱体 Target
2.创建词汇表Yellow材质球
3.将材质球挂载到Target物体上
4.创建脚本MouseMove.cs
MouseMove.cs代码
using UnityEngine; /* 让物体完全跟随鼠标 */ public class MouseMove : MonoBehaviour { [Header("主相机")] [Tooltip("主相机")] /// <summary> /// 主相机 /// </summary> public Camera m_mainCamera; [Header("目标物体")] [Tooltip("目标物体")] /// <summary> /// 目标物体 /// </summary> public Transform m_target; void Start() { isDown = false; targetWTSP = m_mainCamera.WorldToScreenPoint(m_target.position); } /// <summary> /// 是否按下 /// </summary> private bool isDown; /// <summary> /// 记录初始化时候target世界坐标转屏幕坐标时候的位置 WTSP==WorldToScreenPoint /// </summary> private Vector3 targetWTSP; void Update() { if (Input.GetMouseButtonDown(0)) { isDown = true; } if (Input.GetMouseButtonUp(0)) { isDown = false; } } private void LateUpdate() { if (isDown) { Vector3 mouseVec3 = m_mainCamera.ScreenToWorldPoint( new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetWTSP.z) ); m_target.position = mouseVec3; } } }
5.新建一个空物体Script,并将MouseMove.cs脚本挂载上去,再将相机和Target物体拖拽到脚本上
完毕!