Search Unity

Question I need help with my scrolling background

Discussion in 'Scripting' started by PanicMedia, Apr 22, 2021.

  1. PanicMedia

    PanicMedia

    Joined:
    Dec 6, 2020
    Posts:
    37
    I am currently working on a platformer and I was working a parallax background however The three sets of background images are all being spawned on top of each other and the background isn't looping like it's supposed to.

    this is the tutorial I used:


    here's my code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Parralax : MonoBehaviour
    6. {
    7.     private float length, startpos;
    8.     public GameObject cam;
    9.     public float parallaxEffect;
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.         startpos = transform.position.x;
    14.         length = GetComponent<SpriteRenderer>().bounds.size.x;
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void FixedUpdate()
    19.     {
    20.         float temp = (cam.transform.position.x * (1-parallaxEffect));
    21.         float dist = (cam.transform.position.x * parallaxEffect);
    22.  
    23.         transform.position = new Vector3(startpos = dist, transform.position.y, transform.position.z);
    24.  
    25.         if(temp > startpos + length) startpos += length;
    26.         else if (temp < startpos - length) startpos -= length;
    27.     }
    28. }
    29.  
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    When doing a tutorial, always double check your code vs theirs.

    upload_2021-4-22_9-42-14.png
     
    Kurt-Dekker and Sphinks like this.