-2

I have been trying to make an infinitely repeating background. Found this piece below but it goes horizontally instead of vertically. I tried rotating my sprites but it didn't work, also changed the x values with y and the loop stopped happening. I'm stuck trying to figure out a solution.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RepeatBg : MonoBehaviour
{

    private BoxCollider2D boxCollider;

    private Rigidbody2D rb;

    private float width;

    private float speed = -3f;

    // Start is called before the first frame update
    void Start()
    {
        boxCollider = GetComponent<BoxCollider2D>();
        rb = GetComponent<Rigidbody2D>();

        width = boxCollider.size.x;
        rb.velocity = new Vector2(speed,0);
    }

    // Update is called once per frame
    void Update()
    {
        if (transform.position.x<-width)
        {
            Reposition();
        }
    }
    private void Reposition()
    {
        Vector2 vector = new Vector2(width * 2f, 0);
        transform.position = (Vector2)transform.position + vector;
    }
}

1 Answers1

0

You need to change all "vertical stuff" to horizontal.

Add a member variable

private float height;

In method Start set

height = boxCollider.size.y;
rb.velocity = new Vector2(0, speed);

In method Update change the condition to

if (transform.position.y < -height)

In method Reposition set

Vector2 vector = new Vector2(0, height * 2f);
Jiří Skála
  • 649
  • 9
  • 23