c# - 如何在 Unity 3D 中将对象移动到鼠标的 z 和 y 坐标
问题描述
我试图让橙色框跟随我的鼠标。但是使用我当前的脚本,它只向我的鼠标方向移动大约四分之一单位,然后停止。我完全被困住了
using UnityEngine.EventSystems;
using UnityEngine;
public class drag : MonoBehaviour
{
private void Update()
{
Vector2 mousePos = Input.mousePosition;
Vector3 worldPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, Camera.main.nearClipPlane));
transform.position = new Vector3(transform.position.x, worldPos.y, worldPos.z);
}
}
有什么帮助吗?这是为了游戏果酱,我还有大约 48 小时要完成。谢谢!
解决方案
干得好:
private void Update()
{
// Get the mouse position
Vector3 mousePos = Input.mousePosition;
// Set the z component of the mouse position to the absolute distance between the camera's z and the object's z.
mousePos.z = Mathf.Abs(Camera.main.transform.position.z - transform.position.z);
// Determine the world position of the mouse pointer
Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
// Update the position of the object
transform.position = worldPos;
}
推荐阅读
- tensorflow - 使用大数据集在 Google Colab TPU 上训练 seq2seq 模型 - Keras
- stack - 为什么6502在写入之前先从堆栈中读取?
- javascript - TypeError:未定义不是对象(评估“this.state”)
- javascript - 将 DOM 元素保存到 localStorage
- c# - Emgu.CV.Util.CvException: 'OpenCV: i < 0' 异常
- kotlin - Kotlin:将函数范围作为参数传递
- c# - 有没有办法使用库专门为 LED 引脚设置值?
- c# - Razor 视图 @model 找不到类型或命名空间名称“x”
- css - EXT JS:css和相对于父容器的位置
- google-sheets-api - Integromat:重命名 Google 表格(单个表格与整个电子表格)