- Home /
A repeating background
I am making a scrolling background that repeats itself along the Y axis, I am sure it is probably just a typo of some sorts but the background is scrolling, but not re-positioning itself at all.
using UnityEngine;
using System.Collections;
public class RepeatingBackground: MonoBehaviour
{
private BoxCollider2D backgroundCollider;
private float backgroundVerticalLength;
private void Awake()
{
backgroundCollider = GetComponent<BoxCollider2D>();
backgroundVerticalLength = backgroundCollider.size.y;
}
private void Update()
{
if (transform.position.y < -backgroundVerticalLength)
{
RepositionBackground();
}
}
private void RepositionBackground()
{
Vector2 backgroundOffSet = new Vector2(0, backgroundVerticalLength * 2f);
transform.position = (Vector2)transform.position + backgroundOffSet;
}
}
Answer by JonPQ · Jan 31, 2018 at 11:20 PM
First off... what moves the background? I can't see any code that add's to the position of the object to move it... are you sure you are not moving the camera and forgetting about the background ? IF you are moving the camera.... you'll need to subtract the cam.position from your background position, then check the Y on that offset, to see when to re-position it.
if you are already doing that in another script... then check this... ....are you sure your offsets are not going backwards instead of forwards... Check your 'IF' in update... try both > and < Or Just add a couple of break points and debug the code as it runs, line by line, you should soon see what it is doing.
Also transform.position is a Vector3, I'm not sure adding Vector2's to it is fully kosher. Slightly ambiguous what is getting added to what.
Answer by CobOfTheCorn · Jan 31, 2018 at 11:37 PM
I have a script that moves the background that is also attached to it. I have two background copies and I am trying to make it to where it takes one and places it in front of the other as the background scroll.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScrollingObject : MonoBehaviour {
private Rigidbody2D rb2d;
// Use this for initialization
void Start ()
{
rb2d = GetComponent<Rigidbody2D>();
rb2d.velocity = new Vector2(0,GameController.instance.scrollSpeed);
}
// Update is called once per frame
void Update ()
{
if (GameController.instance.gameOver == true)
{
rb2d.velocity = Vector2.zero;
}
}
}
Your answer
Follow this Question
Related Questions
How to script a repeating environment texture 3 Answers
Better way for a tile based system 0 Answers
turn based two player bord game 0 Answers
Background on a Quad 1 Answer
how do I create background image? 1 Answer