c# - 为什么将游戏对象的移动限制在相机框架内会阻止移动?

标签 c# unity-game-engine

我试图将游戏对象的移动限制为仅在摄像机 View 内。我能够移动我的父游戏对象:

Vector3 movement = new Vector3(inputX, inputY, 0);
movement *= (Time.deltaTime * speed * smoothTime);
gameObject.GetComponent<Rigidbody>().MovePosition(transform.position + movement);

但是,我的玩家游戏对象在添加下面的代码后似乎停止移动:

Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);
pos.x = Mathf.Clamp01(pos.x);
pos.y = Mathf.Clamp01(pos.y);
transform.position = Camera.main.ViewportToWorldPoint(pos);        

我尝试修改代码以合并这些语句,但我对导致我的游戏对象在相机位置上抖动的逻辑感到困惑:

movement = Camera.main.WorldToViewportPoint(new Vector3(inputX, inputY, transform.position.z));
movement.x = Mathf.Clamp01(movement.x);
movement.y = Mathf.Clamp01(movement.y);
movement *= (Time.deltaTime * speed * smoothTime);
transform.position = Camera.main.ViewportToWorldPoint(movement);
gameObject.GetComponent<Rigidbody>().MovePosition(transform.position + movement);

我在想我需要直接限制运动并固定我的 x 和 y 位置。我不知道我错过了什么。

最佳答案

这里的问题是,当您调用WorldToViewportPoint()时,你应该向它传递一个世界位置。但是,您正在传递 Vector3(inputX, inputY ...) ,并且可推测的 inputX 和 inputY 不是世界坐标。

Vector3 movement = new Vector3(inputX, inputY, 0);
movement *= (Time.deltaTime * speed * smoothTime);

// Calculate the 'to-be' final position
Vector3 position = transform.position + movement;

// Clamp that position
Vector3 screenCoordinates = Camera.main.WorldToViewportPoint(position);
screenCoordinates.x = Mathf.Clamp01(screenCoordinates.x);
screenCoordinates.y = Mathf.Clamp01(screenCoordinates.y);

position = Camera.main.ViewportToWorldPoint(screenCoordinates);

// then finally set it
gameObject.GetComponent<Rigidbody>().MovePosition(position);

最后,您可能想缓存您的 Camera.main和你的GetComponent<Rigidbody>因为对每一帧进行这些调用都是昂贵的。

关于c# - 为什么将游戏对象的移动限制在相机框架内会阻止移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65374503/

相关文章:

c# - gridview 上的复选框事件?

c# - HttpActionContext 唯一请求标识符

c# - session 在关闭 jquery 对话框后过期

c# - 如何按程序将文本附加到生成的游戏对象?

ios - 等待主机连接

c# - 将模型中的数据对象集合绑定(bind)到 View 中的一组控件 (WPF)

c# - 错误 : a certificate chain processed, 但在根错误 .Net Framework 4.7 中终止

c# - 如何从另一个脚本访问任何创建的游戏对象的属性 Unity C# 2D

unity-game-engine - 使用 HDRP 渲染管线

android - 使用 Unity 播放器/引擎在现有 Android 应用程序中加载 3d