Unity相机仅在X、Y负坐标下跟随玩家,正坐标下失效,请问问题出在哪里?
相机跟随异常问题排查与修复
我看了你的相机跟随代码,立刻发现了问题所在——你在处理X、Y轴正方向偏移时,错误地修改了临时变量deltaX/deltaY,而没有把值赋给delta的对应分量,导致正方向的偏移根本没有传递给相机的位置更新。
问题详细分析
看你代码里的X轴处理逻辑:
if (transform.position.x < lookAt.position.x) { deltaX = deltaX - boundX; // 这里只是修改了deltaX变量,没给delta.x赋值! } else { delta.x = deltaX + boundX; }
当玩家在相机的正X方向(transform.position.x < lookAt.position.x)时,你计算出了需要移动的偏移量,但只是存在了deltaX里,没有把这个值赋给delta.x,所以delta.x始终是0,相机不会移动。而负方向的分支正确赋值给了delta.x,所以负坐标下能正常跟随。Y轴的问题完全一样。
修复后的代码
把正方向分支里的deltaX/deltaY赋值改成给delta.x/delta.y赋值即可:
public Transform lookAt; public float boundX = 0.15f; public float boundY = 0.05f; private void LateUpdate() { Vector3 delta = Vector3.zero; // 检查是否处于X轴边界范围内 float deltaX = lookAt.position.x - transform.position.x; if (deltaX > boundX || deltaX < -boundX) { if (transform.position.x < lookAt.position.x) { delta.x = deltaX - boundX; // 修正:赋值给delta.x } else { delta.x = deltaX + boundX; } } // 检查是否处于Y轴边界范围内 float deltaY = lookAt.position.y - transform.position.y; if (deltaY > boundY || deltaY < -boundY) { if (transform.position.y < lookAt.position.y) { delta.y = deltaY - boundY; // 修正:赋值给delta.y } else { delta.y = deltaY + boundY; } } transform.position += new Vector3(delta.x, delta.y, 0); }
额外优化建议
你还可以简化一下逻辑,用更简洁的方式计算偏移,比如用Mathf.Clamp相关思路处理边界,避免变量赋值错误:
private void LateUpdate() { Vector3 targetPos = lookAt.position; Vector3 currentPos = transform.position; // X轴跟随:超出边界时移动到边界外的位置 float deltaX = targetPos.x - currentPos.x; if (Mathf.Abs(deltaX) > boundX) { currentPos.x += deltaX - Mathf.Sign(deltaX) * boundX; } // Y轴跟随:同理 float deltaY = targetPos.y - currentPos.y; if (Mathf.Abs(deltaY) > boundY) { currentPos.y += deltaY - Mathf.Sign(deltaY) * boundY; } transform.position = new Vector3(currentPos.x, currentPos.y, transform.position.z); }
这样代码可读性更高,也能减少类似低级错误的出现概率。
内容的提问来源于stack exchange,提问作者ColdCosmicSoup
相关产品推荐
相关产品推荐

