我有一个C#脚本控制我的主摄像头在我正在进行的塔防游戏的自上而下的视角 . 据我所知,Screen.width应该随屏幕尺寸缩放,因此使用Screen.width - 所需的边框粗细作为相机移动的限定符应该从限定方向的屏幕边缘厚度边缘的指定位置触发 .
我遇到的问题是,无论屏幕尺寸如何,将鼠标移到屏幕中间点的右侧都会导致相机向该方向移动 . 这是专门用于扫描右 - 左行为与预期相同的代码 .
我猜测的是左侧是有效的,因为屏幕像素数从左下角开始,由于某种原因,Screen.width正在限制它的缩放比例相对于Screen.height,但我无法找到其他人在3d项目中遇到同样的问题,这让我觉得我忽视了一些愚蠢的事情 . 我看到有关正交相机适用于二维项目的一些事情,但我想我会在这里拍摄一些东西以防万一有人知道他们的头顶是什么 .
这是我的代码:
using UnityEngine;
public class CameraController : MonoBehaviour {
private bool doMovement = true;
public float panSpeed = 20f;
public float panBorderThickness = 10f;
public float scrollSpeed = 5f;
public float minY = 40f;
public float maxY = 120f;
void Update () {
if (GameManager.gameIsOver)
{
this.enabled = false;
return;
}
if (Input.GetKeyDown(KeyCode.Escape))
doMovement = !doMovement;
if (!doMovement)
return;
if (Input.GetKey("d") || Input.mousePosition.x >= Screen.height - panBorderThickness)
{
transform.Translate(Vector3.forward * panSpeed * Time.deltaTime, Space.World);
}
if (Input.GetKey("a") || Input.mousePosition.x <= panBorderThickness)
{
transform.Translate(Vector3.back * panSpeed * Time.deltaTime, Space.World);
}
if (Input.GetKey("s") || Input.mousePosition.y <= panBorderThickness)
{
transform.Translate(Vector3.right * panSpeed * Time.deltaTime, Space.World);
}
if (Input.GetKey("w") || Input.mousePosition.y >= Screen.width - panBorderThickness)
{
transform.Translate(Vector3.left * panSpeed * Time.deltaTime, Space.World);
}
float scroll = Input.GetAxis("Mouse ScrollWheel");
Vector3 pos = transform.position;
pos.y -= scroll * 1000 * scrollSpeed * Time.deltaTime;
pos.y = Mathf.Clamp(pos.y, minY, maxY);
transform.position = pos;
}
}
1 回答
使用
Screen.height-Input.mousePosition.y
屏幕位置和输入的y相反,它不是你的左右你的向上 .