我的游戏场景中有一个魔方(玩家)。我编写了一个C#脚本来限制立方体的移动(使用Mathf.Clamp()),这样它就不会离开屏幕。
下面是脚本中的FixedUpdate()方法
private void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.velocity = movement * speed;
rb.position = new Vector3(
Mathf.Clamp (rb.position.x, x_min, x_max),
0.5f,
Mathf.Clamp(rb.position.z, z_min, z_max)
);
}x_min、x_max、z_min、z_max的值分别为-3、3、-2、8。
问题
脚本运行良好,但是我的播放器(立方体)可以在负X-AXIS中移动到-3.1个单位(如果我一直按左箭头按钮),负X-AXIS的这个值要高出0.1个单位(其他轴也是如此)。显然,当我停止按按钮时,它会夹紧-3.1到-3。

Mathf.Clamp())不把立方体限制在-3单位的第一位?发布于 2017-05-02 13:27:28
发布于 2017-05-02 13:25:36
你的问题可能是因为你设定了速度然后定位,但是在下一个框架之前,统一会把速度加到你的物体位置上。这就是为什么它最终损失了0.1单位。
要解决这个问题,尝试将物体的速度重置为零,如果它即将离开你的边界。
发布于 2017-05-02 14:02:09
你已经知道发生这种事的原因了。
为了解决这个问题,您可以使用此代码防止多维数据集超出您的边界:
private void FixedUpdate() {
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
// Get new position in advance
float xPos = rb.position.x + movement.x * speed * Time.fixedDeltaTime;
float zPos = rb.position.z + movement.z * speed * Time.fixedDeltaTime;
// Check if new position goes over boundaries and if true clamp it
if (xPos > x_max || xPos < x_min) {
if (xPos > x_max)
rb.position = new Vector3(x_max, 0, rb.position.z);
else
rb.position = new Vector3(x_min, 0, rb.position.z);
movement.x = 0;
}
if (zPos > z_max || zPos < z_min) {
if (zPos > z_max)
rb.position = new Vector3(rb.position.x, 0, z_max);
else
rb.position = new Vector3(rb.position.x, 0, z_min);
movement.z = 0;
}
rb.velocity = movement * speed;
}https://stackoverflow.com/questions/43738537
复制相似问题