我是C#的初学者,想让玩家在一定范围内(2-7)放大相机。我的代码可以放大或缩小,但是当缩放的级别达到2或7时,它将不允许任何输入。
如果我的代码乱七八糟,或者解决方案很简单,我会事先道歉,因为我只做了几天。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class CameraZoom : MonoBehaviour
{
public CinemachineVirtualCamera cvc;
public float scrollSpeed = 10;
void Start()
{
cvc = GetComponent<CinemachineVirtualCamera>();
}
void Update()
{
if (Input.GetAxis("Mouse ScrollWheel") != 0f && cvc.m_Lens.OrthographicSize >= 2 && cvc.m_Lens.OrthographicSize <= 7)
{
cvc.m_Lens.OrthographicSize -= Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
}
else
{
Debug.Log("Cannot zoom any further.");
}
}
}发布于 2022-01-22 11:32:11
您需要分三个步骤将逻辑分开。
这看起来就像
private void Update ()
{
// 1. get and handle input
var newSize = cvc.m_Lens.OrthographicSize - Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
// 2. Ensure range
if(newSize < 2f) newSize = 2f;
else if(newSize > 7f) newSize = 7f;
// 3. Assign
cvc.m_Lens.OrthographicSize = newSize;
}你要找的是Mathf.Clamp
您只需在一行中完成整个过程:
private void Update ()
{
cvc.m_Lens.OrthographicSize = Mathf.Clamp(cvc.m_Lens.OrthographicSize - Input.GetAxis("Mouse ScrollWheel") * scrollSpeed, 2f, 7f);;
}确保输入始终被处理,但大小保证保持在2和7之间。
发布于 2022-01-22 06:29:59
我假设cvc.m_Lens.OrthographicSize只在所示的代码中更改。
在我看来,这似乎是一个简单的逻辑问题。一旦你设置
cvc.m_Lens.OrthographicSize to a value that is >=2 or <=7 这发生在您的if中,字段不再更改,您不能再进入if,因为您的条件总是错误的。
我的建议是在if之外确定cvc.m_Lens.OrthographicSize的建议新值,将其保存到变量中,然后决定是否要赋值。就像这样:
void Update()
{
// get proposed new size
var newOrthographicSize = cvc.m_Lens.OrthographicSize - Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
if (Input.GetAxis("Mouse ScrollWheel") != 0f {
Debug.Log("Use scroll wheel to operate.");
return;
}
if (newOrthographicSize >= 2 && newOrthographicSize <= 7)
{
cvc.m_Lens.OrthographicSize = newOrthographicSize;
}
else
{
Debug.Log("Cannot zoom any further.");
}
}https://stackoverflow.com/questions/70810051
复制相似问题