之前我们研究过UI拖拽跟随鼠标移动的方法:https://blog.youkuaiyun.com/mr_five55/article/details/135562325
但是该方法不适合3D场景。
假如我们要通过鼠标拖拽3D物体移动,那么可以使用以下控制方法:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragObject : MonoBehaviour
{
private Vector3 offset;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
// 3D场景移动物体
private void OnMouseDown()
{
// 由于物体为3维世界坐标,鼠标的坐标是2维屏幕坐标,所以需要进行相关坐标转换,此处涉及3个步骤
// 1、先把物体的世界坐标转换成3维屏幕坐标,再获取物体的三维屏幕坐标的Z轴坐标:Camera.main.WorldToScreenPoint(transform.position).z
// 2、把鼠标的2维坐标转换成3维世界坐标
// 3、当前物体位置减去鼠标3维世界坐标,获取它们之间的距离
offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.WorldToScreenPoint(transform.position).z));
}
private void OnMouseDrag()
{

最低0.47元/天 解锁文章
1050

被折叠的 条评论
为什么被折叠?



