Unity_Lesson

Input.GetAxis以外の方法として、

Unityにおける各入力メソッドの役割についての説明。

1. Input.GetKey

if (Input.GetKey(KeyCode.W))
{
    // Wキーが押されている間の処理
}


2. Input.GetButton

if (Input.GetButton("Jump"))
{
    // "Jump"ボタンが押されている間の処理
}

3. Input.GetKeyDown

if (Input.GetKeyDown(KeyCode.Space))
{
    // スペースキーが押された瞬間の処理
}


4. Input.GetKeyUp

if (Input.GetKeyUp(KeyCode.Space))
{
    // スペースキーが離された瞬間の処理
}


まとめ



サンプルプログラム(Input.GetKeyを使用)

この例では、Input.GetKeyを使って、WASDキーや矢印キーでキャラクターを移動させる方法を示します。

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed = 5f; // プレイヤーの移動速度

    void Update()
    {
        // プレイヤーの移動ベクトルを初期化
        Vector3 movement = Vector3.zero;

        // Wキーまたは上矢印キーが押されたら前に移動
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
        {
            movement += Vector3.forward;
        }
        // Sキーまたは下矢印キーが押されたら後ろに移動
        if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
        {
            movement += Vector3.back;
        }
        // Aキーまたは左矢印キーが押されたら左に移動
        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            movement += Vector3.left;
        }
        // Dキーまたは右矢印キーが押されたら右に移動
        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            movement += Vector3.right;
        }

        // プレイヤーを移動させる
        transform.Translate(movement * speed * Time.deltaTime);
    }
}


解説