- Home /
Limit a 2D camera movement to the insides of a circlecollider2D
Hi, I'm trying to pan a 2D camera (orthographic) and clamping its position to the limits of a circlecollider2D. The camera is moving fine and it's currently limited to the space inside a circlecollider2d radius of a gameobject in my scene. The problem is that it only works when the collider is at Vector2.zero.
// Camera
public void Pan(Vector2 movement, Vector3 center, float radius)
{
panVect = transform.position;
panVect += new Vector3(movement.x, movement.y, 0) * panSpeed;
panVect = Vector3.ClampMagnitude(panVect, radius);
transform.position = panVect;
}
This is the function to pan the camera around. The movement is the input, the center and radius are relative to the collider. My question is how should I use the center to clamp the camera movement when the center is not at Vector2.zero?
Answer by CiberX15 · Apr 23, 2020 at 12:56 AM
What I would do is clamp the individual x and y values of the vector, that way you can clamp them relative to your center as such:
// Camera
public void Pan(Vector2 movement, Vector3 center, float radius)
{
panVect = transform.position;
panVect += new Vector3(movement.x, movement.y, 0) * panSpeed;
panVect.x = Mathf.Clamp(panVect, -(center.x + radius), center.x + radius)
panVect.y = Mathf.Clamp(panVect, -(center.y + radius), center.y + radius)
transform.position = panVect;
}
It can however be done with Vector3.ClampMagnitude but you need to add a separate vector3 var to track your camera's local position relative to the center. Then you would add that local value to Center as such.
Vector3 localPos = vector3.zero;
// Camera
public void Pan(Vector2 movement, Vector3 center, float radius)
{
panVect = localPos;
panVect += new Vector3(movement.x, movement.y, 0) * panSpeed;
panVect = Vector3.ClampMagnitude(panVect, radius);
transform.position = center + panVect;
}
Thank you for the response. None of the above solutions worked so, I changed the approach and did a little different. Ins$$anonymous$$d of moving the transform of the camera I move its target position (its not relevant for this problem but its for code clearance).
// Camera
public void Pan(Vector2 movement, Vector3 center, float radius)
{
Vector3 step = new Vector3(movement.x, movement.y, 0) * panSpeed;
float distance = Vector3.Distance(lerp.targetPos + step, center);
if (distance < radius)
{
lerp.targetPos += step;
}
}
The camera is always lerping to the target position so, when I pan the target the camera follows smoothly. As for the code I calculate the distance between the next position the camera can lerp to and check if the position is inside the radius. If it is it can go. Otherwise it does nothing. I appreciate you comment but it was not working. I tried that yesterday and in paper it makes sense but in practice I was not getting the results I wanted.