aboutsummaryrefslogtreecommitdiff
blob: 025bf407754c281e7beabdc3e9fe3bc9eca91c36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LevelScrolling : MonoBehaviour
{
  public int UpdateRate = 1;
  public List<Transform> Obstacles;
  public Transform Background;

  private Vector3 initialBgPos;
  private float[] backgroundSize;

  // Start is called before the first frame update
  void Start()
  {
    ResizeBackground();
  }

  // Update is called once per frame
  void Update()
  {

  }

  void FixedUpdate()
  {
    MoveBackground();
    MoveObstacles();
  }

  private void ResizeBackground()
  {
    var sr = Background.GetComponent<SpriteRenderer>();
    if (sr == null) return;

    Background.localScale = new Vector3(1, 1, 1);

    var width = sr.sprite.bounds.size.x;
    var height = sr.sprite.bounds.size.y;

    var worldScreenHeight = Camera.main.orthographicSize * 2.0;
    var worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;

    var finalHeight = (float)(worldScreenHeight / height);
    var finalWidth = (float)(worldScreenWidth / width);

    Background.localScale = new Vector3(finalHeight, finalHeight, 1);

    var viewportX = Camera.main.ViewportToWorldPoint(new Vector3(0, 1, 0)).x;
    Background.position = new Vector3(viewportX * -1, 0, 0);
    initialBgPos = Background.position;
  }

  private void MoveObstacles()
  {
    foreach (var o in Obstacles)
    {
        o.Translate(new Vector2(0.01f * UpdateRate, 0));
    }
  }

  private void MoveBackground()
  {
    if (Background.position.x > -initialBgPos.x)
      Background.Translate(new Vector2(0.01f * UpdateRate, 0));
    else Background.position = initialBgPos;
  }
}