Navmeshagent与飞行VR教程 VR资源

spinscrew 2017-12-06 16:25:58
先看看效果图:
 

一个是飞行的兵种,一个是步兵,同时向鼠标的点击点出发。
Navmesh实现步兵的寻路不是难事,在此略过不表,关键是飞行的兵种怎么实现。在这里先说说原理:
飞行的兵种不使用Navmesh功能,是直接移动到目的点。关键要解决的是如何保持兵种的飞行高度。这个解决的办法是从兵的点向下发一个射线,然后碰到物体,改变兵种的高度和碰到的物体一定的距离,这样就可以实现保持兵种的飞行高度。在上下的过程中,还可以用插值来让过程更加的连贯。
下面是兵种的控制代码:
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
 
public enum MoveType
{
    Walk,
    Fly
}
 
public class Player : MonoBehaviour {
 
    public MoveType _MoveType;
    public float _Height;
 
 
    private NavMeshAgent agent;
    private Vector3 desPos;
    private bool flyBool = false;
 
 
    void Start () {
        agent = transform.GetComponent<NavMeshAgent>();
        if (_MoveType == MoveType.Fly) agent.enabled = false;
    }
     
 
    void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            Move();
        }
 
        if (_MoveType == MoveType.Fly)
        {
            RaycastHit hit;
            if (Physics.Raycast(transform.position, -transform.up, out hit))
            {
                transform.position = new Vector3(transform.position.x, hit.point.y + _Height, transform.position.z);
 
            }
            if (flyBool)
            {
                transform.position = Vector3.MoveTowards(transform.position, desPos, Time.deltaTime *5);
                if (Vector3.Distance(transform.position, desPos) < _Height + 0.1f)
                {
                    flyBool = false;
                }
            }
 
        }
 
 
    }
 
    void Move()
    {
 
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//在鼠标所在的屏幕位置发出一条射线
        RaycastHit hit;
        if (Physics.Raycast(ray.origin, ray.direction, out hit))
        {
 
            if (hit.collider.gameObject.tag == "Terrain")
            {//设置地形Tag为Terrain 
                switch (_MoveType)
                {
                    case MoveType.Walk:
                        agent.SetDestination(hit.point);
                        break;
                    case MoveType.Fly:
                        desPos = hit.point;
                        flyBool = true;
                        break;
                }
                       
                    
            }
 
 
        }
    }
}
99VR视界二维码
热门推荐
Hot Recommended
在线客服