Menu
CoddyTech

ジャンプ、スライド、または回避

Coddyの「Unityゲーム:スカイレーン」コースのレッスン 10/20。

障害物が1種類なら答えも1つです。ジャンプです。3種類の場合は、3つの問いかけになります。

道路上の赤い障害物、高さ y 0.5:飛び越えます。高さ y 1.95 に吊るされた黄色いバー:その下を滑り抜けます。高さ y 1.5 で高さ3ユニットの紫色の壁:レーンを変更します。

2つの短いメソッドで、種類番号をプレハブと高さに変換します。

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、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プレイグラウンド