前言:在实际项目开发中涉及很多鼠标与场景中物体交互功能的开发,如鼠标接触物体、鼠标脱离接触物体、鼠标直接拖动物体等功能的开发,在这里开这么一个帖子,简单记录一下这些功能简单的实现。
1.在场景中添加一个Cube物体。
2.创建一个脚本,命名为Mouse_Drag,脚本代码如下所示。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mouse_Drag : MonoBehaviour
{
//主场景Camera
public Camera mCamera;
//景深
public float depth = 10f;
/// <summary>
/// 鼠标接触物体
/// </summary>
void OnMouseEnter()
{
this.transform.localScale = new Vector3(1.3f,1.3f,1.3f);
}
/// <summary>
/// 鼠标离开物体
/// </summary>
void OnMouseExit()
{
this.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
}
/// <summary>
/// 鼠标停在物体上
/// </summary>
void OnMouseOver()
{
this.transform.Rotate(Vector3.up,45*Time.deltaTime,Space.Self);
}
/// <summary>
/// 鼠标拖拽物体
/// </summary>
void OnMouseDrag()
{
MoveObject_fixdepth();
}
/// <summary>
/// 鼠标拖拽物体的实现逻辑
/// </summary>
void MoveObject_fixdepth()
{
Vector3 mouseScreen = Input.mousePosition;
mouseScreen.z = depth;
Vector3 mouseWorld = mCamera.ScreenToWorldPoint(mouseScreen);
this.transform.position = mouseWorld;
}
}
3.将此脚本挂载到需要拖拽的cube上,并将主场景Camera拖拽到物体的脚本中。
4.点击运行,发现已经实现了上述脚本实现的功能。
总结:上述脚本实现的功能较为简单,只是简单实现了上述功能,在实际开发中可以将此功能运用到实际项目中。