EDIT:
I was completely wrong about this. Cam.ScreenToWorldPoint gave me a negative x value. The Camera is not at 0, 0, 0.
Correct Code-
void Start() {
// Create the image twice
Images [0] = Instantiate (Image);
Images [1] = Instantiate (Image);
// Set boths images to be a child of this transform
Images [0].gameObject.transform.parent = transform;
Images [1].gameObject.transform.parent = transform;
// Place both images on the screen at the top left
Vector3 DesiredStart = Cam.ScreenToWorldPoint (new Vector3 (0, Cam.pixelHeight, 0));
float startX = DesiredStart.x;
float startY = DesiredStart.y;
Images [0].gameObject.transform.position = new Vector3 (startX, startY, 5);
Images [1].gameObject.transform.position = new Vector3 (Image.sprite.bounds.size.x + startX, startY, 5);
}
ORIGINAL:
I’ve got a scrolling background that goes from right to left. I’m going to have a long background image that connects at either end. To have the scrolling uninterrupted and seamless I’m going to have the BackgroundController create two copies of the image and move them together, right to left, until the first image is completely out of view. Then, I will reset the Background GameObject transform position and everything should line up without any hiccups.
All is good EXCEPT the sprite bounds width is incorrect for some reason. Here is my BackgroundController-
using UnityEngine;
using System.Collections;
public class BackgroundScrollController : MonoBehaviour {
public float scrollSpeed;
public SpriteRenderer Image;
public Camera Cam;
private SpriteRenderer[] Images = new SpriteRenderer[2];
void Start() {
// Create the image twice
Images [0] = Instantiate (Image);
Images [1] = Instantiate (Image);
// Set boths images to be a child of this transform
Images [0].gameObject.transform.parent = transform;
Images [1].gameObject.transform.parent = transform;
// Place both images on the screen at the top left
Images [0].gameObject.transform.position = Cam.ScreenToWorldPoint(new Vector3(0, Cam.pixelHeight, 15));
Images [1].gameObject.transform.position = Cam.ScreenToWorldPoint(new Vector3(0, Cam.pixelHeight, 15));
// Place the second image to the right of the first image
Images [1].gameObject.transform.position = new Vector3(Image.sprite.bounds.size.x, Images [1].gameObject.transform.position.y, 5);
}
void Update () {
if (!WorldGlobals.Paused ()) {
Vector3 newPosition = transform.position;
newPosition.x -= scrollSpeed * Time.deltaTime;
transform.position = newPosition;
if(transform.position.x <= -Images[0].sprite.bounds.size.x) {
transform.position = new Vector3(0, 0, 0);
}
}
}
}
Which looks fine. But when the images are laid out, the second image has come gap before it-
Why isn’t sprite.bounds.size.x
giving me the correct width of the background?
Here is my test background-