I’ve been trying to solve this problem on my own for a couple hours and I can’t seem to figure it out, so I thought I’d ask it here.
I have three background layers (with layer3 being the farthest) and I want them to scroll depending on where you are in the level. (e.g. when in the exact center they all are centered, on the left their left edges match the left side of the screen, etc.)
However, instead they all start perfectly centered with the camera, when they should have their left edges aligned with the left side of the screen. (the camera is at it’s farthest left position at the beginning)
Then, as the camera moves, they move super fast, like in the screenshots provided.
This is about ten units into the level and you can already see their edges.
Then at just over halfway through the level, they are way offscreen. (They should be about centered here.)
How can I edit my math to make it work correctly?
Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BackgroundHandler : MonoBehaviour {
float lC, rC, tC, bC, hDist, vDist, hMid, vMid, hSpan, vSpan;
float sprSize;
SpriteRenderer rend;
Transform cam;
void Start () {
rend = GetComponent<SpriteRenderer>();
cam = GameObject.Find("Main Camera").transform;
if (rend.sprite.name == "layer3")
{
sprSize = 2;
}
if (rend.sprite.name == "layer2")
{
sprSize = 3;
}
if (rend.sprite.name == "layer1")
{
sprSize = 4;
}
lC = GameObject.Find("PConstLeft").transform.position.x + 6.5f;
rC = GameObject.Find("PConstRight").transform.position.x - 6.5f;
tC = GameObject.Find("PConstUp").transform.position.y - 5f;
bC = GameObject.Find("PConstDown").transform.position.y + 5f;
hSpan = rC - lC;
vSpan = tC - bC;
hMid = lC + (hSpan / 2);
vMid = bC + (vSpan / 2);
}
void Update () {
hDist = -(hMid - cam.position.x);
vDist = -(vMid - cam.position.y);
transform.position = new Vector2(
(hMid + lC + hDist) * sprSize,
(vMid + bC + vDist) * sprSize
);
}
}
Explanation:
lC, rC, bC,
andtC
are the extents of the camera movement, left, right, bottom and top.
hDist
and vDist
are the horizontal and vertical distances of the camera and middle of the scene.
hMid
and vMid
are the midpoints of the constraints.
hSpan
and vSpan
are the total distance from constraint to constraint.
sprSize
is the size (in screens) of the background image.
If anyone can help with my faulty math or has any clarifying questions please let me know!