So I am making a vertical scroller, and after just finishing up my script that will keep creating my background I am getting an odd error, or rather bug. It might just be in my code, but I can’t figure it out and I need a second (or a dozen) extra pairs of eyes. To start things off here is my code:
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(SpriteRenderer))] // Makes sure there is a sprite as part of the gameObject
public class Tiling : MonoBehaviour {
public int offsety = 2; // The offset so no wierd errors
public bool hasBuddy = false; // Checks if we need to instantiate / spawn stuff
public bool reverseScale = false; // Used if object isn't tilable
private float spriteHeight = 0f; // The height of the element
private Camera cam;
private Transform myTransform;
void Awake ()
{
cam = Camera.main;
myTransform = transform;
}
void Start () {
SpriteRenderer sRenderer = GetComponent<SpriteRenderer>();
spriteHeight = sRenderer.sprite.bounds.size.y;
}
// Update is called once per frame
void Update ()
{
// Calculate where the camera can see
float camVerticalExtend = cam.orthographicSize * Screen.width/Screen.height;
// Calculate the y pos where the camera can see the edge of the sprite
float edgeVisiblePositionBottom = (myTransform.position.y - spriteHeight/2) + camVerticalExtend;
// Check if we need a new sprite
if (cam.transform.position.y <= edgeVisiblePositionBottom + offsety && hasBuddy == false)
{
MakeNewBuddy(-1);
hasBuddy = true;
}
else if (cam.transform.position.y >= edgeVisiblePositionBottom + offsety)
{
hasBuddy = false;
}
}
// How we spawn new sprites!!!
void MakeNewBuddy (int buddyValue)
{
// Where should the new sprite go? (this is how we calculate it)
Vector3 newPosition = new Vector3 (myTransform.position.x, myTransform.position.y + spriteHeight * buddyValue, myTransform.position.z);
Transform newBuddy = Instantiate (myTransform, newPosition, myTransform.rotation) as Transform;
// if its not tileable, then lets reverse the x, y, and z. (just makes it look nice)
if (reverseScale == true)
{
newBuddy.localScale = new Vector3 (newBuddy.localScale.x*-1, newBuddy.localScale.y*-1, newBuddy.localScale.z*-1);
}
// Makes sure there arent a ton of different layer values for each new sprite created.
newBuddy.parent = myTransform.parent;
// It now has a sprite buddy! So lets not spawn a bunch more until we need one.
if (buddyValue < 0){
newBuddy.GetComponent<Tiling>().hasBuddy = true;
}
}
}
The sprites are getting downscaled by what appears to be different amounts when they are cloned. The scaling on my background clouds is turned down to roughlly .84, and my buildings to the side of the cloud is scaled down to a scaling of .76. Here is a screenshot of what is occuring.
Anyway after finally getting my scrolling to work I was saddened by this bug maybe you can make me happy! All replies are welcome!
Thanks a bunch!