본문 바로가기
Unity

[Unity 2D] 원근감(Parallax) 있는 무한 배경 만들기

by imagineer_jinny 2021. 9. 25.

2D 종스크롤 슈팅 - 원근감있는 무한 배경 만들기 [유니티 기초 강좌 B33] - YouTube

 

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

public class Background : MonoBehaviour
{
    public float speed;
    public int startIndex;
    public int endIndex;
    public Transform[] sprites;

    float viewHeight;

    private void Awake()
    {
        //orthographicSize: orthographic 카메라 Size
        viewHeight = Camera.main.orthographicSize *2;
    }

    void Update()
    {
        Move();
        Scrolling();
    }
    void Move()
    {
        Vector3 curPos = transform.position;
        Vector3 nextPos = Vector3.down * speed * Time.deltaTime;
        transform.position = curPos + nextPos;
    }

    void Scrolling()
    {
        if (sprites[endIndex].position.y < viewHeight * (-1))
        {
            Vector3 backSpritePos = sprites[startIndex].localPosition;
            Vector3 fromtSpritePos = sprites[endIndex].localPosition;
            sprites[endIndex].transform.localPosition = backSpritePos + Vector3.up * 10;

            //이동이 완료되면 EndIndex, StartIndex 갱신
            int startIndexSave = startIndex;
            startIndex = endIndex;
            endIndex = (startIndexSave - 1 == -1) ? sprites.Length - 1 : startIndexSave - 1;
        }
    }
    
}

댓글