LoginSignup
23

More than 5 years have passed since last update.

Unity クリックした位置にObjectを移動させる

Last updated at Posted at 2015-04-03

Unity5 Personal Edition
環境: Mac OSX
言語: C#

Navigationについて
Unity マニュアル

ナビゲーション メッシュを生成する

1.マップを作る

2.作ったマップ(object)をStaticにする

3.メニューのWindow > Navigation を選択、Navigation タブが開く
タブの下にある「Bake」を押す

4.移動させるオブジェクトにNav Mesh Agent コンポーネントを追加する
(Add Component > Navigation > Nav Mesh Agent)

これでNavigationを利用できる状態になる

Script

Move.cs

using UnityEngine;
using System.Collections;

public class Move : MonoBehaviour {
    private NavMeshAgent agent;

    private RaycastHit hit;
    private Ray ray;

    void Start () {
        agent = GetComponent<NavMeshAgent>();
    }

    void Update () {
        if (Input.GetMouseButtonDown(0)){
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit, 100f)){
                agent.SetDestination(hit.point);
            }       
        }
    }
}

このScriptを移動させるオブジェクトにアタッチすれば完了です。

Physics.Raycast(ray, out hit, 100f)

  • 第一引数は Ray(架空の線)の開始地点
  • 第二引数は Rayが衝突したオブジェクトの情報を取得
  • 第三引数は Ray(架空の線)を飛ばす距離

agent.SetDestination(hit.point)

  • agent.SetDestination() 引数に目的地の座標
  • hit.point Rayが衝突したオブジェクトのワールド座標

Raycastについて
Unity スクリプティング API

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
23