64 lines
2.2 KiB
C#
64 lines
2.2 KiB
C#
using UnityEngine;
|
|
|
|
namespace Spaceshooter.Environment
|
|
{
|
|
public class Background : MonoBehaviour
|
|
{
|
|
[Header("Scroll Settings")]
|
|
[SerializeField] private float scrollSpeed = 1.5f;
|
|
|
|
private float bgWidth;
|
|
private Transform firstBg;
|
|
private Transform secondBg;
|
|
|
|
private void Start()
|
|
{
|
|
firstBg = transform;
|
|
|
|
// Calculate width from SpriteRenderer or standard Renderer
|
|
SpriteRenderer sr = GetComponent<SpriteRenderer>();
|
|
if (sr != null && sr.sprite != null)
|
|
{
|
|
bgWidth = sr.bounds.size.x;
|
|
}
|
|
else
|
|
{
|
|
Renderer r = GetComponent<Renderer>();
|
|
bgWidth = (r != null) ? r.bounds.size.x : 27f;
|
|
}
|
|
|
|
if (bgWidth <= 0.1f) bgWidth = 27f;
|
|
|
|
// Automatically clone this background to tile right next to it
|
|
GameObject cloneObj = Instantiate(gameObject, transform.parent);
|
|
cloneObj.name = gameObject.name + "_LoopClone";
|
|
Destroy(cloneObj.GetComponent<Background>()); // prevent recursion
|
|
|
|
secondBg = cloneObj.transform;
|
|
secondBg.position = new Vector3(firstBg.position.x + bgWidth - 0.05f, firstBg.position.y, firstBg.position.z);
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
float moveStep = scrollSpeed * Time.deltaTime;
|
|
|
|
if (firstBg != null) firstBg.position += Vector3.left * moveStep;
|
|
if (secondBg != null) secondBg.position += Vector3.left * moveStep;
|
|
|
|
// When either background scrolls off-screen to the left, wrap it seamlessly to the right
|
|
if (firstBg != null && secondBg != null)
|
|
{
|
|
if (firstBg.position.x <= -bgWidth)
|
|
{
|
|
firstBg.position = new Vector3(secondBg.position.x + bgWidth - 0.05f, firstBg.position.y, firstBg.position.z);
|
|
}
|
|
|
|
if (secondBg.position.x <= -bgWidth)
|
|
{
|
|
secondBg.position = new Vector3(firstBg.position.x + bgWidth - 0.05f, secondBg.position.y, secondBg.position.z);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|