c# - 带位置夹的 SmoothDamp

标签 c# unity-game-engine

我有一个摄像头跟踪使用“SmoothDamp”的玩家,但我希望阻止摄像头超出背景 Sprite 的范围。

我可以使用“SmoothDamp”单独执行此操作,但不能使用“Mathf.Clamp”。

transform.position = Vector3.SmoothDamp(transform.position, targetPos, ref velocity, smoothTime);

bgBounds = GameObject.Find("Background").GetComponentInChildren<SpriteRenderer>();
bottomLeftLimit = bgBounds.sprite.bounds.min;
topRightLimit = bgBounds.sprite.bounds.max;

transform.position = new Vector3(Mathf.Clamp(transform.position.x, bottomLeftLimit.x, topRightLimit.x), Mathf.Clamp(transform.position.y, bottomLeftLimit.y, topRightLimit.y), transform.position.z);

最佳答案

为了确保正交相机的边界不会留下边界,您需要将相机 View 的范围作为夹子的填充包含在内。

您可以使用camera.orthgraphicSizecamera.aspect来获取相机 View 的范围。

// Clamp the target position to be within the boundaries

float cameraVertExtent = camera.orthographicSize;
float cameraHorizExtent = camera.orthographicSize * camera.aspect;

Vector3 clampedTargetPos = new Vector3(
        Mathf.Clamp(targetPos.x, bottomLeftLimit.x+cameraHorizExtent, topRightLimit.x-cameraHorizExtent), 
        Mathf.Clamp(targetPos.y, bottomLeftLimit.y+cameraVertExtent, topRightLimit.y-cameraVertExtent),
        transform.position.z
        );

// SmoothDamp to the clamped target position.
transform.position = Vector3.SmoothDamp(transform.position, clampedTargetPos, ref velocity, smoothTime);

如果您没有使用正交相机,则需要找到相机 View 的边缘与背景相交的位置,并从那里解决必要的填充问题。

关于c# - 带位置夹的 SmoothDamp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53505383/

相关文章:

unity-game-engine - Unity,修改标准着色器以随机翻转纹理?

ios - Unity 性能峰值达到 30 FPS

c# - Unity手机SSL连接错误

javascript - 将 Javascript 转换为 C# 问题

c# - 在 UWP Xaml 中创建和填充 NxN 网格

c# - 如何将 C++ 对象传递给 C# 类库

c# - DateTime.Kind 未在 WCF 中返回

c# - 如何在 C++ 中创建和初始化 double 的 SAFEARRAY 以传递给 C#

c# - ASP.Net Web API 模型构造函数绑定(bind) - 调用了错误的构造函数

unity-game-engine - Unity 3d Vuforia不显示3d模型目标对象