Question by
Nycrael · Oct 04, 2015 at 01:07 PM ·
camera-movementclampmathf.clamp
2D Camera shakes when player move fast
Hi, all! I got a little problem: my camera shakes when player move fast. Here is code: public GameObject target;
public Vector2
Margin,
Smoothing;
public BoxCollider2D Bounds;
private Vector3
_min,
_max;
public bool IsFollowing {get; set;}
Camera camera;
public void Start()
{
_min = Bounds.bounds.min;
_max = Bounds.bounds.max;
IsFollowing = true;
camera = GetComponent<Camera> ();
}
public void Update()
{
var x = transform.position.x;
var y = transform.position.y;
if (IsFollowing)
{
if (Mathf.Abs(x - target.transform.position.x) > Margin.x)
x = Mathf.Lerp(x, target.transform.position.x, Smoothing.x * Time.deltaTime);
if (Mathf.Abs(y - target.transform.position.y) > Margin.y)
y = Mathf.Lerp(y, target.transform.position.y, Smoothing.y * Time.deltaTime);
}
var cameraHalfWidth = camera.orthographicSize * ((float) Screen.width / Screen.height);
x = Mathf.Clamp (x, _min.x + cameraHalfWidth, _max.x - cameraHalfWidth);
y = Mathf.Clamp (y, _min.y + camera.orthographicSize, _max.y - camera.orthographicSize);
transform.position = new Vector3(x, y, transform.position.z);
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612040007im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Clamp camera within bounds of a Polygon Collider? 1 Answer
How to clamp transform.Rotate values? 0 Answers
Clamping when Zoom changes? 0 Answers
Camera clamps to the world scale, not local :c 1 Answer
MathF.clamp not working! 1 Answer