そらい研究室

関心のある物事について、少し深堀りして解説しています。

MENU

Unity 矢印キーの入力とマウス・スマホタップを判定するサンプルコード

矢印キーの入力判定を行う

if(Input.GetKey("right")){
    //右キーを押したら実行したい処理
}

if(Input.GetKey("left")){
    //左キーを押したら実行したい処理
}

if(Input.GetKey("up")){
    //上キーを押したら実行したい処理
}

if(Input.GetKey("down")){
    //下キーを押したら実行したい処理
}

使用例

下は、矢印キーでキャラクターを動かすコード。 「CharactorMove」というスクリプト名で、キャラクターのゲームオブジェクトにアタッチするとすぐに使える。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharactorMove : MonoBehaviour
{
    float speed = 1f / 50f;

    void Update()
    {
        if (Input.GetKey("right"))
        {
            this.transform.Translate(speed, 0, 0);
        }

        if (Input.GetKey("left"))
        {
            this.transform.Translate(-speed, 0, 0);
        }

        if (Input.GetKey("up"))
        {
            this.transform.Translate(0, speed, 0);
        }

        if (Input.GetKey("down"))
        {
            this.transform.Translate(0, -speed, 0);
        }
    }
}

これはあるていど知識がある人向けだが、配列とfor文を使って同じ処理をさせる方法もある。余力があればチャレンジしてみてほしい。

sorai-lab.hateblo.jp

スペースキーの入力判定を行う

if(Input.GetKey("space")){
    //スペースキーを押したら実行したい処理
}

マウスクリック、またはスマホでのタップ判定を行う

if(Input.GetMouseButtonDown(0)){
    //左クリックが押された瞬間(またはスマホでのタップ発生時)に実行したい処理
}
if(Input.GetMouseButtonDown(1)){
    //右クリックが押された瞬間に実行したい処理
}

if(Input.GetMouseButton(0)){
    //左クリックが押されている間(またはスマホでのタップ中)に実行したい処理
}
if(Input.GetMouseButton(1)){
    //右クリックが押されている間に実行したい処理
}

if(Input.GetMouseButtonUp(0)){
    //左クリックが離された瞬間(またはスマホでのタップをやめたとき)に実行したい処理
}
if(Input.GetMouseButtonUp(1)){
    //右クリックが離された瞬間に実行したい処理
}

応用:オブジェクトの位置をマウスドラッグやスマホタップで動かす

「押されたとき」、押されている間」、「離されたとき」の三つの判定を利用して、オブジェクトをつかんで動かす機能を実現している。

Vector2 fromPos;
Vector2 middlePos;
Vector2 toPos;

void Update()
{

    if (Input.GetMouseButtonDown(0))
    {
        fromPos = this.transform.position;
        transform.position = fromPos;
    }
    else if (Input.GetMouseButton(0))
    {
        middlePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = middlePos;
    }
    else if (Input.GetMouseButtonUp(0))
    {
        toPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = toPos;
    }
}