- Home /
2D boundaries for player gameobject not moving with scrolling camera
The code I currently have has worked great keeping the player within the boundaries of the screen when my camera is static, but when I start having it scroll along the X-axis the boundaries I have stay the same and the camera leaves the player behind. I've tried figuring out a way to update the boundaries with the transform of the camera's X-axis with very little luck. I should mention this is a completely 2D game. Is there something obvious I'm missing or should I rethink how I'm going about this? Thanks!
public class ShipBoundaries : MonoBehaviour
{
public Camera MainCamera;
private Vector2 boundaries;
private float objectWidth;
private float objectHeight;
void Start()
{
boundaries = MainCamera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, MainCamera.transform.position.z));
objectWidth = transform.GetComponent<SpriteRenderer>().bounds.extents.x;
objectHeight = transform.GetComponent<SpriteRenderer>().bounds.extents.y;
}
void LateUpdate()
{
Vector3 viewPos = transform.position;
viewPos.x = Mathf.Clamp(viewPos.x, boundaries.x * -1 + objectWidth, boundaries.x - objectWidth);
viewPos.y = Mathf.Clamp(viewPos.y, boundaries.y * -1 + objectHeight, boundaries.y - objectHeight);
transform.position = viewPos;
}
}
Answer by rufopufo · Jun 28, 2019 at 07:25 AM
Hi there,
I suppose that your boundaries are simple colliders attached to the background or to some other gameObject in the Scene.
If you make a children in your Main Camera, and make this children be your "Boundaries", it should move along with the Camera.
Hope it helps.