도로 움직이기
Coddy의 Unity 게임: 스카이 레인 코스 레슨. 20개 중 6번째.
러너 게임에서는 플레이어가 제자리에 있고 세계가 플레이어 쪽으로 다가옵니다. 카메라와 플레이어를 계속 앞으로 움직여도 되지만, 숫자가 끝없이 커지므로 도로를 움직이면 모든 것을 0 근처에 유지할 수 있습니다.
속도는 게임 전체에 적용되므로 GameManager에 둡니다. Road는 Start에서 속도를 한 번 가져오고 매 프레임 속도를 읽습니다.
float step = game.speed * Time.deltaTime;
foreach (Transform chunk in chunks)
{
chunk.position += Vector3.back * step;
}Vector3.back은 (0, 0, -1)입니다. 카메라 쪽을 향합니다. 나중에 조각들을 움직이려면 Road가 조각들을 List<Transform>에 기억해 두어야 합니다.
챌린지
쉬움GameManager에public float startSpeed = 10f;와public float speed;를 추가하고, Start에서speed = startSpeed로 설정하세요.Road에private List<Transform> chunks = new List<Transform>();를 추가하고(using System.Collections.Generic;포함),private GameManager game;도 추가하세요.- Start에서
game = FindFirstObjectByType<GameManager>();로 설정하고, 새로 만든 각 조각을chunks에 추가하세요. - 위와 같이
Update를 작성하세요.
직접 해보기
using UnityEngine;
public class Runner : MonoBehaviour
{
public float laneWidth = 2.5f;
public float laneSpeed = 16f;
public float jumpHeight = 1.6f;
public float gravity = -40f;
public float slideTime = 0.7f;
public int lane;
private CharacterController controller;
private float fallSpeed;
private float slide;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) lane = Mathf.Max(-1, lane - 1);
if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) lane = Mathf.Min(1, lane + 1);
bool jump = Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Space);
if (jump && controller.isGrounded)
{
fallSpeed = Mathf.Sqrt(jumpHeight * -2f * gravity);
StopSlide();
}
if ((Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) && controller.isGrounded)
{
slide = slideTime;
Resize(0.5f);
}
if (slide > 0f)
{
slide -= Time.deltaTime;
if (slide <= 0f) StopSlide();
}
if (controller.isGrounded && fallSpeed < 0f) fallSpeed = -2f;
fallSpeed += gravity * Time.deltaTime;
float targetX = lane * laneWidth;
float x = Mathf.MoveTowards(transform.position.x, targetX, laneSpeed * Time.deltaTime);
Vector3 move = new Vector3(x - transform.position.x, fallSpeed * Time.deltaTime, 0f);
controller.Move(move);
}
void StopSlide()
{
if (transform.localScale.y < 1f) Resize(1f);
slide = 0f;
}
void Resize(float height)
{
controller.enabled = false;
transform.position += Vector3.up * (height - transform.localScale.y);
transform.localScale = new Vector3(1f, height, 1f);
controller.enabled = true;
}
}
Unity 게임: 스카이 레인의 모든 레슨
직접 연습해 보세요: Unity 플레이그라운드