LoginSignup
0
0

More than 1 year has passed since last update.

【はんちゃん備忘録】ボタンを押してる間オブジェクトを特定の位置に移動させる

Last updated at Posted at 2021-06-01

1. 初めに

この記事はUnity初心者の私が覚えたことを忘れないためのメモのようなものです。

2. やる事

Movie.gif
上のgif のように、ボタンを押している間は特定の位置まで移動させ、離すと初期位置に戻るようにする。この動画では2つのボタンで上下移動、離すと中央に戻るようになっています。

それを応用して作ったゲームがこちらです。
PlayMovie.gif

これを応用したゲーム

3. スクリプト

Player.cs
using UnityEngine;

public class Player : MonoBehaviour
{
    public float speed = 1; //移動スピード
    private float step;
    private Vector3 direction1 = new Vector3(0, 0, 0);   //ボタンを押してない時の位置(初期位置)
    private Vector3 direction2 = new Vector3(0, 2f, 0);   //上ボタンを押した時に移動する位置
    private Vector3 direction3 = new Vector3(0, -2f, 0);  //下ボタンを押した時に移動する位置

    void Start()
    {
        this.gameObject.transform.position = direction1;    //ゲーム開始時に初期位置に移動
    }

    void Update()
    {
        //上ボタンを押した時
        if (Input.GetKey(KeyCode.UpArrow) && !Input.GetKey(KeyCode.DownArrow))
        {
            step = speed * Time.deltaTime;
            this.gameObject.transform.position = Vector3.MoveTowards(transform.position, direction2, step);
        }

        //下ボタンを押した時
        else if (Input.GetKey(KeyCode.DownArrow) && !Input.GetKey(KeyCode.UpArrow))
        {
            step = speed * Time.deltaTime;
            this.gameObject.transform.position = Vector3.MoveTowards(transform.position, direction3, step);
        }

        //ボタンを押してない時
        else    
        {
            step = speed * Time.deltaTime;
            this.gameObject.transform.position = Vector3.MoveTowards(transform.position, direction1, step);
        }
    }    
}

上記スクリプトでは、キーボードの右矢印キーを押すとdirection2の位置。左矢印キーを押すとdirection3の位置。何も押していない状態だと初期位置(direction1)へ移動します。

移動速度はスクリプト上でspeedの値を変えるか、アタッチしたオブジェクトのインスペクターから変更してください。

このスクリプトを操作したいオブジェクトにアタッチすれば下のgif画像と同じ動作になります。( speed = 10の場合 )
Movie.gif

Player.cs
        //上ボタンを押した時
        if (Input.GetKey(KeyCode.UpArrow) && !Input.GetKey(KeyCode.DownArrow))
        {
            ...
        }

        //下ボタンを押した時
        else if (Input.GetKey(KeyCode.DownArrow) && !Input.GetKey(KeyCode.UpArrow))
        {
            ...
        }

このif文の条件に!Input.GetKey(KeyCode.DownArrow)および!Input.GetKey(KeyCode.UpArrowを入れているのは、ボタンが同時押しされた場合の対策です。

4. まとめ

以上Unity初心者のメモ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0