1
\$\begingroup\$

I'm trying to make a camera system where the camera never goes outside the edges of the current room (like Link to the Past or Mega Man, for example)

This is what I have right now:

using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public BoxCollider roomBounds;
public Player target;
Vector3 velocity;
float halfHeight,halfWidth;
void Start(){
    halfHeight = Camera.main.orthographicSize;
    halfWidth = halfHeight * Camera.main.aspect;
}
void LateUpdate(){
    Vector3 targetPosition = target.transform.position;
    if (targetPosition.x+halfWidth >= roomBounds.bounds.max.x || targetPosition.x-halfWidth <= roomBounds.bounds.min.x) {
        velocity.x = 0;
    } else {
        velocity.x = targetPosition.x - transform.position.x;
    }
    if (targetPosition.y+halfHeight >= roomBounds.bounds.max.y || targetPosition.y-halfHeight <= roomBounds.bounds.min.y) {
        velocity.y = 0;
    } else {
        velocity.y = targetPosition.y - transform.position.y;
    }
    transform.position += velocity;
}
}

It works on a rudimentary level, but the problem is, whenever you're moving out from a wall after the camera's stopped, it snaps a little to the left or the right, and then goes back. Same vertically.

Any idea as to what might be causing this and how to solve it?

P.S. I know there have been a lot of threads about this kind of system (even one 21 hours ago), but none I've found helped me much.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Clamping the Camera's position at the end of position calculation would fix your problem. Put this code at the end of your ''LateUpdate()'' method.

float finalXPos = Mathf.Clamp(transform. Position.x, roomBounds.bounds.min.x + halfWidth, roomBounds.bounds.max.x - halfWidth);
float finalYPos; // Do the same calculation for Y position.
transform.position = new Vector2(finalXPos, finalYPos);

Note: Code might be little of syntactically (since I cannot test it right now), and also there might be a clamping function for Vector2, which you can search for it.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .