I am making a side scrolling game where the player is able to move left and right. The background scrolls with the player using this script
Scrolling background Script
void FixedUpdate ()
{
Vector3 point = Camera.main.WorldToViewportPoint(target.position);
Vector3 delta = target.position - Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f,1));
Vector3 destination = transform.position + delta;
destination.y = 0;
Vector3 velocity = Vector3.zero;
transform.position = destination;
//Debug.Log(destination);
}
I am having two problems with this however as I have more then 1 background sprite as the character progresses through the level (tiled if you will). I have them name for example “bg1”,“bg2”,“bg3” what I need to accomplish is only allowing the camera to scroll in a positive direction while the player can still be at the edge of the Viewport. As you will see in the next script for the first background tile I can simply set the cam’s X position to 0 and that works fine. However, when the camera stops from the conditional statement it snaps into place and when it passes the conditional statement it snaps back giving the game a very jagged appearance.
Here is the script below.
check bounds script
public class scriptCheckBounds : MonoBehaviour {
private float _xMin;
private float _xMax;
void Update()
{
float _xMin = GameObject.Find("bg1").GetComponent<SpriteRenderer>().bounds.min.x;
float _camMinX = Camera.main.ViewportToWorldPoint(new Vector3(0, 0)).x;
Debug.Log(_xMin);
if (_camMinX <= _xMin)
{
float _vel = 0.0f;
Debug.Log("bad cam");
var _camPos = Camera.main.transform.position;
_camPos.x = 0;
Camera.main.transform.position = _camPos;
}
else
{
Debug.Log("good cam");
}
}
}
So to sum it up my questions are as follows:
- How will I set the camera to stay in the center of each up coming tile as the player passes into it.
- How do I avoid having the camera snap into place when the conditional statement is fired.
I appreciate the help and time from the community thank you very much!