Menu
CoddyTech

슬라이드

Coddy의 Unity 게임: 하늘길 코스 레슨. 21개 중 4번째.

일부 장애물은 너무 높이 걸려 있어 점프할 수 없습니다. 달리기 캐릭터는 그 아래로 미끄러져 지나갑니다. 슬라이드하면 잠시 동안 달리기 캐릭터의 키가 절반으로 줄어듭니다.

오브젝트를 축소하면 CharacterController도 함께 축소되지만, 가운데를 기준으로 축소되므로 발이 도로에서 반 단위만큼 떠 있게 됩니다. 달리기 캐릭터를 같은 반 단위만큼 아래로 이동시키세요. 직접 이동할 때는 컨트롤러를 꺼야 합니다. 그렇지 않으면 다음 Move가 변경 사항을 되돌립니다.

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;
}

타이머 slide는 슬라이드 시간을 측정합니다. 시간이 다 되면 StopSlide로 달리기 캐릭터가 다시 일어섭니다.

void StopSlide()
{
    if (transform.localScale.y < 1f) Resize(1f);
    slide = 0f;
}
challenge icon

챌린지

쉬움

러너가 장애물 아래로 미끄러져 지나가게 하세요.

  1. 위와 같이 public float slideTime = 0.7f;, private float slide;, Resize 및 StopSlide를 추가하세요.
  2. 지면에 있을 때 S 키 또는 아래쪽 화살표 키를 누르면 slide = slideTime으로 설정하고 Resize(0.5f)를 호출하세요.
  3. slide > 0f인 동안 매 프레임 Time.deltaTime만큼 값을 줄이세요. 값이 0이 되면 StopSlide()를 호출하세요.
  4. 점프하면 미끄러지기가 끝납니다. 러너가 점프할 때 StopSlide()를 호출하세요.

‘플레이’를 누른 다음 S 키를 누르세요. 러너가 잠시 몸을 낮췄다가 다시 일어섭니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

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 int lane;

    private CharacterController controller;
    private float fallSpeed;

    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);
        }

        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);
    }
}

Unity 게임: 하늘길의 모든 레슨

직접 연습해 보세요: Unity 플레이그라운드