我已经尝试了一段时间了,我只需要做到这一点,这样我就可以使用相机的视场进行放大和缩小。当我尝试这样做时,什么也没有发生。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraZoom : MonoBehaviour
{
private Camera cameraFreeWalk;
public float zoomSpeed = 20f;
public float minZoomFOV = 10f;
public void ZoomIn()
{
if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
cameraFreeWalk.fieldOfView -= zoomSpeed;
if (cameraFreeWalk.fieldOfView < minZoomFOV)
{
cameraFreeWalk.fieldOfView = minZoomFOV;
}
}
}
}发布于 2021-04-19 03:28:50
(1)由于没有调用ZoomIn()函数,因此不会发生任何事情。您应该将输入检查移动到Update()方法中,因为Unity在每一帧中都会调用它,然后当鼠标滚轮打开时,您可以调用ZoomIn()函数。
private void Update()
{
if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
ZoomIn();
}
}
public void ZoomIn()
{
cameraFreeWalk.fieldOfView -= zoomSpeed;
if (cameraFreeWalk.fieldOfView < minZoomFOV)
{
cameraFreeWalk.fieldOfView = minZoomFOV;
}
}(2)需要设置cameraFreeWalk字段。您可以通过添加属性"SerializeField“使其在编辑器中可见,然后在编辑器中将相机拖动到暴露的字段中……
[SerializeField]
private Camera cameraFreeWalk;..。或者,您可以自动收集摄像头组件。在这个例子中,我们告诉Unity在同一个游戏对象上必须有一个摄像头组件,并且我们收集了一个对它的引用。如果您想要格外小心,可以通过执行Assert()检查来检查您是否真的获得了引用。由于RequiredComponent属性,这有点多余,但我喜欢检查我正在处理的所有字段。
[RequireComponent(typeof(Camera))]
public class cameraZoom : MonoBehaviour
{
....
private void Awake()
{
cameraFreeWalk = GetComponent<Camera>();
Assert.IsNotNull(cameraFreeWalk);
}(3)最后,为了确保脚本能够正常工作,你还应该在Awake()方法中,检查是否有人没有将相机更改为正交模式--因为这样就不会使用FOV了。就我个人而言,我喜欢Assert()方法,如您所见…
Assert.IsFalse(cameraFreeWalk.orthographic, "There isn't a FOV on an orthographic camera.");完整的解决方案应该是这样的……
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
[RequireComponent(typeof(Camera))]
public class cameraZoom : MonoBehaviour
{
[SerializeField]
private Camera cameraFreeWalk;
public float zoomSpeed = 20f;
public float minZoomFOV = 10f;
public float maxZoomFOV = 160f;
private void Awake()
{
cameraFreeWalk = GetComponent<Camera>();
Assert.IsNotNull(cameraFreeWalk);
Assert.IsFalse(cameraFreeWalk.orthographic, "There isn't a FOV on an orthographic camera.");
}
private void Update()
{
if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
ZoomIn();
}
else if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
ZoomOut();
}
}
public void ZoomIn()
{
cameraFreeWalk.fieldOfView -= zoomSpeed;
if (cameraFreeWalk.fieldOfView < minZoomFOV)
{
cameraFreeWalk.fieldOfView = minZoomFOV;
}
}
public void ZoomOut()
{
cameraFreeWalk.fieldOfView += zoomSpeed;
if (cameraFreeWalk.fieldOfView > maxZoomFOV)
{
cameraFreeWalk.fieldOfView = maxZoomFOV;
}
}
}https://stackoverflow.com/questions/67151415
复制相似问题