장애물
Coddy의 Unity 게임: 스카이 레인 코스 레슨. 20개 중 9번째.
이제 도로에는 피해야 할 무언가가 필요합니다. 각 조각에는 무작위 차선의 가운데에 장애물이 하나씩 놓입니다. 이를 처리하는 메서드는 Fill이며, Start에서 새 조각마다 호출되고 조각이 다시 맨 앞으로 돌아올 때마다 다시 호출됩니다.
플레이어에게 잠시 여유를 주기 위해 처음 두 조각은 비워 둡니다. Road는 made에 채운 조각의 수를 기록합니다.
void Fill(Transform chunk)
{
made++;
if (made <= safeChunks) return;
int lane = Random.Range(-1, 2);
Place(chunk, barrierPrefab, lane, 0.5f, 0f);
}Random.Range(-1, 2)는 -1, 0 또는 1을 반환합니다. 정수를 사용할 때는 두 번째 숫자가 선택되지 않습니다.
재활용된 조각에는 이전 장애물이 그대로 남아 있습니다. Clear는 태그가 있는 모든 자식을 제거합니다. 바닥, 점선, 가장자리에는 Untagged 태그가 있으므로 그대로 남습니다.
void Clear(Transform chunk)
{
foreach (Transform child in chunk)
{
if (!child.CompareTag("Untagged")) Destroy(child.gameObject);
}
}챌린지
쉬움Road에public GameObject barrierPrefab;,public int safeChunks = 2;및private int made;를 추가하세요.Place(chunk, prefab, lane, y, z)를 작성하세요. 이 함수는chunk.position + new Vector3(lane * laneWidth, y, z)위치에prefab.transform.rotation을 적용해 프리팹을 조각의 자식으로 만듭니다.- 위와 같이
Fill과Clear를 작성하세요. - Start에서 각 조각에 대해
Fill(chunk)을 호출하고, 조각이 맨 앞으로 이동할 때Clear(chunk); Fill(chunk);을 호출하세요.
직접 해보기
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 플레이그라운드