Input.GetAxis以外の方法として、
Input.GetKeyInput.GetButtonInput.GetKeyDownInput.GetKeyUpInput.GetKeytrueを返します。true、そうでなければfalse。if (Input.GetKey(KeyCode.W))
{
// Wキーが押されている間の処理
}
Input.GetButtontrueを返します。true、そうでなければfalse。if (Input.GetButton("Jump"))
{
// "Jump"ボタンが押されている間の処理
}
Input.GetKeyDowntrueを返します。true、そうでなければfalse。if (Input.GetKeyDown(KeyCode.Space))
{
// スペースキーが押された瞬間の処理
}
Input.GetKeyUptrueを返します。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を使って、各方向への移動ベクトルを簡潔に作成しています。