본문 바로가기

Unity

[Unity] 플레이어를 이용한 선택적 무한 배경(1)

728x90

[Unity] 플레이어가 바라보는 방향으로 Ray를 만들어보자의 연장이다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class BackgroundScrolling : MonoBehaviour
{
    public float speed;
    public Transform[] backgrounds;
 
    float leftPosX = 0f;
    float rightPosX = 0f;
 
    float xScreenHalfSize;
    float yScreenHalfSize;

 

  • speed 배경들이 움직일 속도를 정의한 변수이다.
  • backgrounds 배경들을 담아줄 변수이다.
  • leftPosX 배경의 끝 x좌표를 담아줄 변수이다.
  • rightPosX 배경의 시작 x좌표를 담아줄 변수이다.
  • xScreenHalfSize 게임 화면의 x좌표 절반을 담아줄 변수이다.
  • yScreenHalfSize 게임 화면의 y좌표 절반을 담아줄 변수이다.

 

1
2
3
4
5
6
7
8
void Start()
    {
        yScreenHalfSize = Camera.main.orthographicSize;
        xScreenHalfSize = yScreenHalfSize * Camera.main.aspect;
 
        leftPosX = -(xScreenHalfSize * 2);
        rightPosX = xScreenHalfSize * 2 * backgrounds.Length;
    }

 

start() 함수 코드이다. 백그라운드 스크롤링에 사용하는 변수들을 초기화해준다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 public void OnRightMove()
    {
        for (int i = 0; i < backgrounds.Length; i++)
        {
            backgrounds[i].position += new Vector3(-speed, 00* Time.deltaTime;
 
            if (backgrounds[i].position.x < leftPosX)
            {
                Vector3 nextPos = backgrounds[i].position;
                nextPos = new Vector3(nextPos.x + rightPosX, nextPos.y, nextPos.z);
                backgrounds[i].position = nextPos;
            }
        }
    }

 

Update를 사용하여 배경들의 좌표를 speed만큼 계속 이동시켜준다. 이동 중에 배경의 x좌표가 leftPosX보다 작아졌다면 배경이 화면에서 사라졌다는 것을 의미하므로 배경의 x좌표에 rightPosX만큼을 이동시켜주어 다시 화면의 시작 쪽에 위치하게 해주는 해주는 것이 위의 코드 내용이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 public void OnLeftMove()
    {
        for (int i = 0; i < backgrounds.Length; i++)
        {
            backgrounds[i].position += new Vector3(speed, 00* Time.deltaTime;
 
            if (backgrounds[i].position.x > -leftPosX)
            {
                Vector3 nextPos = backgrounds[i].position;
                nextPos = new Vector3(nextPos.x - rightPosX, nextPos.y, nextPos.z);
                backgrounds[i].position = nextPos;
            }
        }
    }
}

 

OnRightMove와 다른 점은 5, 7, 10행이다. 위의 코드들을 전부 작성해주고 다음 사진처럼 inspector창을 지정해준다.

 

inspector창

728x90