我试图将游戏对象的移动限制为仅在摄像机 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/