Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Infinite Level, how to avoid imprecision?

Discussion in '2D' started by Monsterwald, Oct 27, 2021.

  1. Monsterwald

    Monsterwald

    Joined:
    Jan 19, 2020
    Posts:
    68
    I have this very simple script, whenever my level part reaches the minimum X coordinate it will get transported to the maximum X coordinate

    However from time to time there are some gaps in it, it isn't really precise and I don't really know how to make it more precise.

    Code (CSharp):
    1. public class MovingLevel : MonoBehaviour
    2. {
    3.     [SerializeField] float speed = 20;
    4.  
    5.     private void Update()
    6.     {
    7.         transform.Translate(Vector2.right * -speed * Time.deltaTime);
    8.  
    9.         if (transform.position.x <= -60.00f)
    10.         {
    11.             transform.position = new Vector2(30.00f, transform.position.y); //I know, hardcoding is evil
    12.         }
    13.     }
    14. }



    Edit
    works now.... I changed a bit, first instead of having the code on my 3 level parts, I created a level manager, the level parts as child objects and changed the script. I found this strange System.Linq, which has some useful functions.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.Linq;
    5.  
    6. public class MovingLevel : MonoBehaviour
    7. {
    8.     [SerializeField] float speed = 20;
    9.     [SerializeField] List<Transform> levels = new List<Transform>();
    10.  
    11.     private void Update()
    12.     {
    13.         foreach (Transform l in levels)
    14.         {
    15.             l.Translate(Vector2.right * -speed * Time.deltaTime);
    16.         }
    17.  
    18.         if (levels[levels.Count - 1].position.x <= -60.00f)
    19.         {
    20.             levels[levels.Count - 1].position = new Vector2(levels[0].position.x + 30, levels[levels.Count - 1].position.y);
    21.  
    22.             var moveToFirst = levels.Last();
    23.             levels.RemoveAt(levels.Count - 1);
    24.             levels.Insert(0, moveToFirst);
    25.         }
    26.     }
    27. }
     
    Last edited: Oct 27, 2021