So I’ve been trying to set up a platformer game, and I’ve been trying to setup a camera similar to games like Mario or Megaman, where it won’t scroll outside the current level. Basically, the idea is that I first cast a ray from the corner of the screen. If it doesn’t hit the background, another ray is cast towards the background. It uses the distance to the background to calculate how far to move back. Unfortunately, this doesn’t work to well, as the camera instead bounces back and forth. Here’s the script:
public GameObject Player;
public GameObject Background;
public LayerMask mask;
private float pointDistanceX;
void FixedUpdate ()
{
Ray topRight = Camera.main.ScreenPointToRay(new Vector3(Screen.width, Screen.height, 10));
Ray topLeft = Camera.main.ScreenPointToRay(new Vector3(0, Screen.height, 10));
Ray botLeft = Camera.main.ScreenPointToRay(new Vector3(0, 0, 0));
Ray botRight = Camera.main.ScreenPointToRay(new Vector3(Screen.width, 0, 10));
RaycastHit hit;
Mesh mesh = Background.GetComponent<MeshFilter>().mesh;
transform.position = Player.transform.position + new Vector3(pointDistanceX, 0, -10);
if (!Physics.Raycast(topRight, mask))
{
if (Physics.Raycast(new Vector3(topRight.origin.x, topRight.origin.y, 0), Vector3.left, out hit, mask))
{
pointDistanceX = -Vector3.Distance(hit.point, new Vector3(topRight.origin.x, topRight.origin.y, 0));
Debug.DrawRay(new Vector3(topRight.origin.x, topRight.origin.y, 0), Vector3.right * pointDistanceX, Color.yellow);
}
}
while (transform.position.x < -0.1f)
{
transform.Translate(new Vector3(0.1f, 0, 0) * Time.deltaTime);
}
while (transform.position.y > 2)
{
transform.Translate(new Vector3(0, -0.1f, 0) * Time.deltaTime);
}
while (transform.position.y < -13.5)
{
transform.Translate(new Vector3(0, 0.1f, 0) * Time.deltaTime);
}
}