Menu
CoddyTech

점프, 슬라이드 또는 피하기

Coddy의 Unity 게임: 스카이 레인 코스 레슨. 20개 중 10번째.

장애물 한 종류에는 답이 하나입니다. 점프하세요. 세 종류의 장애물은 세 가지 질문을 합니다:

도로 위의 빨간 장벽, y 0.5: 뛰어넘으세요. y 1.95에 매달린 노란 막대: 아래로 미끄러져 통과하세요. y 1.5에 있고 높이가 3유닛인 보라색 벽: 차선을 바꾸세요.

작은 메서드 두 개가 종류 번호를 프리팹과 높이로 바꿉니다:

GameObject Obstacle(int kind)
{
    if (kind == 0) return barrierPrefab;
    if (kind == 1) return barPrefab;
    return wallPrefab;
}
challenge icon

챌린지

쉬움
  1. barPrefab과 wallPrefab을 Road에 추가하세요.
  2. 위와 같이 Obstacle(kind)을 작성하고, Height(kind)는 kind가 0이면 0.5, kind가 1이면 1.95, 벽이면 1.5로 설정하세요.
  3. Fill에서 int kind = Random.Range(0, 3);을 선택하고, Obstacle(kind)을 Height(kind) 위치에 배치하세요.

직접 해보기

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 플레이그라운드