Search Unity

Canvas image not scrolling seamlessly

Discussion in 'Scripting' started by gsammbunny, Mar 21, 2019.

  1. gsammbunny

    gsammbunny

    Joined:
    Mar 7, 2016
    Posts:
    66
    Good day,

    I've been trying a lot to seamlessly repeat the canvas image but I've failed to do so inside the canvas,

    The problem seems to be inside this function's definition:
    RepositionImage()

    It creates a gap between the two images once it re-positions the image to the canvas.

    Here is the code:
    Code (CSharp):
    1. using UnityEngine;
    2. public class ImageMove : MonoBehaviour
    3. {
    4.     private BoxCollider2D imageCollider;
    5.     private float imageHorizontalLength;
    6.     [SerializeField]
    7.     private float scrollSpeed;
    8.     private Rigidbody2D rb2d;
    9.  
    10.     private void Start()
    11.     {
    12.         rb2d = GetComponent<Rigidbody2D>();
    13.         rb2d.velocity = new Vector2(-scrollSpeed, 0);
    14.     }
    15.  
    16.     private void Awake()
    17.     {
    18.         imageCollider = GetComponent<BoxCollider2D>();
    19.         imageHorizontalLength = imageCollider.size.x;
    20.     }
    21.  
    22.     private void Update()
    23.     {
    24.         if (GetComponent<RectTransform>().offsetMin.x < -imageHorizontalLength)
    25.         {
    26.             rb2d.velocity = Vector2.zero;
    27.             RepositionImage();
    28.             rb2d.velocity = new Vector2(-scrollSpeed, 0);
    29.         }
    30.     }
    31.  
    32.     void RepositionImage()
    33.     {
    34.         Vector2 offset = new Vector2(imageHorizontalLength, 0);
    35.         GetComponent<RectTransform>().anchoredPosition = (Vector2)transform.position + offset;
    36.     }
    37. }
     
    Last edited: Mar 21, 2019
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    Well, it seems like there's two general possibilities:

    1. You're setting the image's position to someplace other than what you intended (e.g. math error, or your image asset doesn't completely fill its bounding box and you forgot to account for that, etc.)

    2. You set the image position correctly, but afterwards something else is moving it. (e.g. a layout group, a physics system, etc.)

    To begin narrowing the problem down, I suggest you add some Debug.Log statements to output the position you are telling the image to go to, and also the position it is actually at a frame or two later, to see whether they are the same. If they're the same, then you have problem #1; if they're different, then you have problem #2.
     
    gsammbunny likes this.