播放器控制摄像机的移动以围绕水平方向看,我正在尝试设置边界,以使摄像机不会过分。但是,当我添加了边界代码时,每当我按下一个按钮移动时,相机就会飞走。
if (Input.GetKey("d"))
{
transform.Translate(new Vector2(camSpeed * Time.deltaTime, 0));
transform.position = new Vector2(Mathf.Clamp(transform.position.x, minX, maxX), 0);
}
if (Input.GetKey("a"))
{
transform.Translate(new Vector2(-camSpeed * Time.deltaTime, 0));
transform.position = new Vector2(Mathf.Clamp(transform.position.x, minX, maxX), 0);
}
if (Input.GetKey("w"))
{
transform.Translate(new Vector2(0, camSpeed * Time.deltaTime));
transform.position = new Vector2(0, Mathf.Clamp(transform.position.y, minY, maxY));
}
if (Input.GetKey("s"))
{
transform.Translate(new Vector2(0, -camSpeed * Time.deltaTime));
transform.position = new Vector2(0, Mathf.Clamp(transform.position.y, minY, maxY));
}
我已将最小值和最大值设置为高于所需的水平,并且无论这些值设置为多少,相机仍然会飞行。
答案 0 :(得分:2)
解释我的评论;而不是每次将W或S移至x时都将x设置为0,而应将钳位移至末尾,并同时钳住x和y(并可能保持Z值?):
if (Input.GetKey("d"))
{
transform.Translate(new Vector2(camSpeed * Time.deltaTime, 0));
}
if (Input.GetKey("a"))
{
transform.Translate(new Vector2(-camSpeed * Time.deltaTime, 0));
}
if (Input.GetKey("w"))
{
transform.Translate(new Vector2(0, camSpeed * Time.deltaTime));
}
if (Input.GetKey("s"))
{
transform.Translate(new Vector2(0, -camSpeed * Time.deltaTime));
}
transform.position = new Vector3(
Mathf.Clamp(transform.position.x, minX, maxX),
Mathf.Clamp(transform.position.y, minY, maxY),
transform.position.z
);