1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Unity3D] Playerの動く範囲を設定する(NavMesh)

Last updated at Posted at 2021-02-11

1, WindowのAI→Navigationを選択
3626E491-D483-42B8-8733-B56EC84CE2ED_4_5005_c.jpeg

2, PlayerにNavMeshAgentを設定する
2330533F-8B04-42BC-BABE-B47E3D48028E.jpeg

3, 下記のスクリプトを作成し、Playerにアタッチする

Mover
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class Mover : MonoBehaviour
{
    [SerializeField] Transform taget;

    // Update is called once per frame
    void Update()
    {
        GetComponent<NavMeshAgent>().destination = taget.position;
    }
}

4, Targetを設定してあげる
F4145B53-8F53-4AAF-876A-407A5AC8EB60.jpeg

5, Meshに含めないobjectなどは、staticにチェックをして選択し、bakeする
5461DD48-B19A-49F1-874A-56308F722462_4_5005_c.jpeg
DF27D531-36AA-4B1A-8611-9F7726531CE2.jpeg

6,Meshの範囲はBakeの設定で変更する
D206FB64-57D5-40C1-893D-7C23C0368B67.jpeg

クリックで操作する

1, クリックでRayを出す。下記スクリプトを書く。

Mover
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class Mover : MonoBehaviour
{
    [SerializeField] Transform taget;

    Ray lastRay; //変数の宣言

    // Update is called once per frame
    void Update()
    {
        // 下記を書く
        if (Input.GetMouseButtonDown(0))
        {
            lastRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        }
        Debug.DrawLine(lastRay.origin, lastRay.direction * 100);

        //
        GetComponent<NavMeshAgent>().destination = taget.position;
    }
}

2, クリックした箇所にPlayerを移動させる

Mover
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class Mover : MonoBehaviour
{
    [SerializeField] Transform taget;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            MoveToCursor();
        }
    }

    private void MoveToCursor()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        bool hasHit = Physics.Raycast(ray, out hit);
        if (hasHit)
        {
            GetComponent<NavMeshAgent>().destination = hit.point;
        }
    }
}
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?