- Home /
Do Canvas Objects behave similarly under the effect of Rigidbody2D when it comes to position checking?
Hello. I am trying to make a scrolling background for a replica of Flappy Bird. I have a Canvas Object with the shown settings:
The Canvas is a parent to two background child image objects with the following code. The idea was to make it such that when the image moved off of the screen by a value equal to its width, it is then teleported back to the right side of the screen. This way two images can be the scrolling background as long as they keep teleporting back to the right side repeatedly. When this script is run, the objects do not teleport at all. Are Canvas/image objects not affected by rigidbody2D transforms in the same way normal game objects are? Or is there something that needs to be changed about the Canvas settings? When I check the scene view when the game is running, the background image objects just keep moving to the left indefinitely far beyond their width (in this case 900). There are videos that show how to do scrolling background, but this approach seemed the simplest and I don't see why it's not working.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BackgroundScroll : MonoBehaviour
{
private Rigidbody2D rigidBody;
private RectTransform background;
private float width;
private float speed = -3;
// Start is called before the first frame update
void Start()
{
rigidBody = GetComponent<Rigidbody2D>();
rigidBody.velocity = new Vector2(speed, 0);
background = GetComponent<RectTransform>();
// Get image width from RectTransform component
width = background.rect.width;
// Display width for troubleshooting
Debug.Log(width);
}
// Update is called once per frame
void FixedUpdate()
{
// if game object was moved further than its width, then teleport
// back to the right side based on width
if (gameObject.transform.position.x <= -width)
{
gameObject.transform.position = new Vector2(width, 0);
Debug.Log("Teleported");
}
}
}
Your answer
Follow this Question
Related Questions
Canvas Movement Code Being Disabled 2 Answers
Why is my default Z set as -4000? 0 Answers
Can't set canvas's backgound in Unity 1 Answer
Canvas not showing 2 Answers
Parallax Lag issue... 0 Answers