闲时以 Unity2D 练手时想实现端游里的场景缩放功能,而网上的代码几乎全是 3D 场景缩放相关,所以我自己编写了个 2D 场景缩放脚本(C#)。
代码如下:
using UnityEngine; using System.Collections; public class SceneScaleController : MonoBehaviour { private float normalCameraSize; private float minCameraSize; private float maxCameraSize; private const float cScaleRange = 0.8f; private const float cScaleFactor = 0.05f; private enum SceneScaleType {sstNone, sstShrink, sstEnlarge}; private SceneScaleType scaleType = SceneScaleType.sstNone; private enum SceneScaleState {sssNormal, sssShrinked, sstEnlarged}; private SceneScaleState scaleState = SceneScaleState.sssNormal; void Start() { normalCameraSize = Camera.main.orthographicSize; minCameraSize = normalCameraSize - cScaleRange; maxCameraSize = normalCameraSize + cScaleRange; } void Update() { if (scaleType == SceneScaleType.sstNone) { float factor = Input.GetAxis("Mouse ScrollWheel"); if ((factor > 0) && (scaleState != SceneScaleState.sssShrinked)) { scaleType = SceneScaleType.sstShrink; } else if ((factor < 0) && (scaleState != SceneScaleState.sstEnlarged)) { scaleType = SceneScaleType.sstEnlarge; } } else if (scaleType == SceneScaleType.sstEnlarge) { float sz = Camera.main.orthographicSize; sz += cScaleFactor; if (scaleState == SceneScaleState.sssNormal) { if (sz >= maxCameraSize) { sz = maxCameraSize; scaleType = SceneScaleType.sstNone; scaleState = SceneScaleState.sstEnlarged; } Camera.main.orthographicSize = sz; } else if (scaleState == SceneScaleState.sssShrinked) { if (sz >= normalCameraSize) { sz = normalCameraSize; scaleType = SceneScaleType.sstNone; scaleState = SceneScaleState.sssNormal; } Camera.main.orthographicSize = sz; } } else if (scaleType == SceneScaleType.sstShrink) { float sz = Camera.main.orthographicSize; sz -= cScaleFactor; if (scaleState == SceneScaleState.sssNormal) { if (sz <= minCameraSize) { sz = minCameraSize; scaleType = SceneScaleType.sstNone; scaleState = SceneScaleState.sssShrinked; } Camera.main.orthographicSize = sz; } else if (scaleState == SceneScaleState.sstEnlarged) { if (sz <= normalCameraSize) { sz = normalCameraSize; scaleType = SceneScaleType.sstNone; scaleState = SceneScaleState.sssNormal; } Camera.main.orthographicSize = sz; } } } }
将脚本挂到 Main Camera 上,滚动鼠标滚轮,场景即发生缩放了。