My current camera is fine for the first half of my prototype, but it’s becoming a problem for later areas. My project is a 2.5D platformer and is set to orthographic and looks at the player/environment from the side. I set up a boundary to prevent the camera from showing the Sky Box, thanks to a tutorial, but it’s only good for following the player left and right. If I want the player to climb up and go down, the camera won’t follow. If I change the player’s position so he spawns outside of the bounds, the camera won’t follow. If I set the camera’s position so it goes back to the player, it no longer moves/follows. If I adjust the boundary, or comment out the clampedY variable in my script, the results can still be pretty mixed. The camera never moves forward ahead either when going back in the opposite direction, which makes seeing what’s approaching very difficult.
I’m not confident or sure how to code the cameras properly, but I could do with some help on setting up the ideal camera system for a 2.5D platformer.
This is the current code I have:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
[SerializeField] GameObject player = null;
public BoxCollider boundBox;
private Vector3 minBounds;
private Vector3 maxBounds;
private Camera theCamera;
private float halfHeight;
private float halfWidth;
private PlayerController thePlayer;
const float m_minY = 2f;
Vector3 targetPosition;
Vector3 cameraOffset;
void Start()
{
theCamera = GetComponent<Camera>();
thePlayer = GetComponent<PlayerController>();
cameraOffset = transform.position - player.transform.position;
minBounds = boundBox.bounds.min;
maxBounds = boundBox.bounds.max;
halfHeight = theCamera.orthographicSize;
halfWidth = halfHeight * Screen.width / Screen.height;
}
void Update()
{
transform.position = player.transform.position + cameraOffset;
targetPosition.y = Mathf.Min(targetPosition.y, m_minY);
float clampedX = Mathf.Clamp(transform.position.x, minBounds.x + halfWidth, maxBounds.x - halfWidth);
//float clampedY = Mathf.Clamp(transform.position.y, minBounds.y + halfHeight, maxBounds.y - halfHeight);
transform.position = new Vector3(clampedX, transform.position.y, transform.position.z);
}
}