c# - Unity 放大和缩小 2D
问题描述
现在已经尝试了一段时间,我只需要完成它,这样我就可以使用相机的 FOV 放大和缩小。当我尝试这个时,没有任何反应。
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;
}
}
}
}
解决方案
(1) 由于没有调用 ZoomIn() 函数,因此不会发生任何事情。您应该将 Input-check 移到 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 在同一个游戏对象上必须有一个 Camera 组件,并且我们在 Awake() 方法中收集对它的引用。如果您想格外小心,请通过 Assert() 检查来检查您是否确实获得了引用。由于RequiredComponent 属性有点多余,但我喜欢检查我正在使用的所有字段。
[RequireComponent(typeof(Camera))]
public class cameraZoom : MonoBehaviour
{
....
private void Awake()
{
cameraFreeWalk = GetComponent<Camera>();
Assert.IsNotNull(cameraFreeWalk);
}
(3) 最后,为了确保脚本正常工作,您还应该在 Awake() 方法中检查是否有人没有将相机更改为 Orthographic - 从那时起将不会使用 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;
}
}
}
推荐阅读
- git - 如何将来自一个 repo 的头部添加到现有头部之上?
- php - Foreach 循环仅在 CSV 导出时为特定行显示一项
- python - 覆盖 Django 表单的元类
- python - pandas - 获取两列之间的最小值并在两列不为空时分配
- linux - 使用目录中的文件名创建 3 列 TAB 文件
- python - Python 中是否有多个积分器同时提供变量积分限制(如 scipy)和高精度(如 mpmath)?
- reactjs - 获取组件以更新状态更改的问题
- php - 合并 2 个数组值
- python - 如何在 django 中修复此搜索栏错误?
- python - Python:体素到 3-D 阵列