using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ParallaxScroller : MonoBehaviour
{
	public static float SPEED_FACTOR = 2f;
	public float speed;
	public Player player;

	private float width = -1f;

	private void OnEnable() {
		player = FindObjectOfType<Player>();
	}

	public float calcWidth() {
		if(width>0f)
			return width;
		
		width = 1f;
		foreach(var sprite in GetComponentsInChildren<SpriteRenderer>()) {
			if(sprite.bounds.size.x > width)
				width = sprite.bounds.size.x;
		}

		return width;
	}

	private void Update() {
		float camHalfWidth = Camera.main.orthographicSize * Screen.width / (float)Screen.height;
		float camXPos = Camera.main.transform.position.x;

		if (transform.position.x+width < camXPos-camHalfWidth*1.5f) Destroy(gameObject);
		if (player != null) {
			transform.position = transform.position + new Vector3(SPEED_FACTOR * speed * Time.deltaTime + (player.parallaxOffset * speed), 0, 0);
		} else {
			transform.position = transform.position + new Vector3(SPEED_FACTOR * speed * Time.deltaTime, 0, 0);
		}
	}
}
