带有定位夹的SmoothDamp

时间:2018-11-27 17:50:17

标签: c# unity3d

我有一个摄像机跟随着使用“ SmoothDamp”的玩家,但是我希望停止摄像机超出背景精灵的范围。

我可以使用“ 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);

1 个答案:

答案 0 :(得分:2)

为了确保正交摄影机的边界不会离开Bounds,您需要将摄影机视图的范围包括在内以填充到夹具上。

您可以使用camera.orthographicSizecamera.aspect来获取相机视图的范围。

// 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);

如果您不使用正交摄影机,则需要找到摄影机视图的边缘与背景相交的位置,并从那里解决必要的填充。