Unity 2Dオブジェクトをクリックした座標に移動させる。その①

何度か思い出したくなるので、

メモ帳代わりに記事として残しておきます。

こんな感じに↑↑動くぞ

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

public class Player : MonoBehaviour
{

    public GameObject player;   //①移動させたいオブジェクト
    Vector3 touchWorldPosition; //②マウスでタッチした箇所の座標を取得
    public int
speed = 5;
    
    void Start()
    {
    }

    
    void Update()
    {
        if (Input.GetMouseButtonDown(0))  //左クリックでif分起動
        {
        Vector3 touchScreenPosition = Input.mousePosition;  //②マウスでタッチした座標をtouchScreenPositionに。
        touchScreenPosition.z = 5.0f;  //②奥行を手前に来るように5.0fを指定。
        Camera camera = Camera.main;  //②
        touchWorldPosition = camera.ScreenToWorldPoint(touchScreenPosition);  //②
        }
    player.transform.position = Vector3.MoveTowards(player.transform.position, touchWorldPosition, speed * Time.deltaTime); playerオブジェクトが, 目的地に移動, 移動速度
    }
}

・インスペクターから移動させたいオブジェクトをプレイヤーにセットする。

・if (Input.GetMouseButtonDown(0))
この行をif (Input.GetMouseButton(0))、に変更する(Downを抜く)と、ワンクリックした場所に移動していたオブジェクトは、長押しでもついていくようになる。

メモ帳代わりに記入しているだけなのでお手柔らかに。

「こういう書き方すると良いんだけどな~」と言う方はコメントによろしくお願いします!



スポンサーリンク



スポンサーリンク

シェアする

  • このエントリーをはてなブックマークに追加

フォローする