Search Unity

Question making a parallax background

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

  1. PanicMedia

    PanicMedia

    Joined:
    Dec 6, 2020
    Posts:
    37
    I'm working on a platformer style game for a college project and I've made a parallax background with help form a tutorial made by Dani (
    ) and I'm having a problem where it doesn't loop properly and some of the assets are clipping through each other. I've attached a picture that hopefully shows this (the background hasn't spawned in yet and the shrine isn't meant to be in front of the rocks and the rocks are meant to be in front of water(light/dark purple rectangle) This is my script
    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.  
    Any help is very much appreciated.
     

    Attached Files: