Input.GetAxis
以外の方法として、
Input.GetKey
Input.GetButton
Input.GetKeyDown
Input.GetKeyUp
Input.GetKey
true
を返します。true
、そうでなければfalse
。if (Input.GetKey(KeyCode.W))
{
// Wキーが押されている間の処理
}
Input.GetButton
true
を返します。true
、そうでなければfalse
。if (Input.GetButton("Jump"))
{
// "Jump"ボタンが押されている間の処理
}
Input.GetKeyDown
true
を返します。true
、そうでなければfalse
。if (Input.GetKeyDown(KeyCode.Space))
{
// スペースキーが押された瞬間の処理
}
Input.GetKeyUp
true
を返します。true
、そうでなければfalse
。if (Input.GetKeyUp(KeyCode.Space))
{
// スペースキーが離された瞬間の処理
}
Input.GetKey
: キーが押されている間ずっとtrue
を返す。Input.GetButton
: Input Managerで設定されたボタンが押されている間ずっとtrue
を返す。Input.GetKeyDown
: キーが押された瞬間のみtrue
を返す。Input.GetKeyUp
: キーが離された瞬間のみtrue
を返す。この例では、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);
}
}
Input.GetKey(KeyCode.W)
はWキーが押されている間、true
を返します。このように、他のキーに対しても同様にチェックすることで、プレイヤーの移動を制御します。Vector3.forward
, Vector3.back
, Vector3.left
, Vector3.right
を使って、各方向への移動ベクトルを簡潔に作成しています。