昨天发布了Naveshagent与飞行,有朋友说关键是差值,所以今天就将差值也加了进去。昨天的版本墙太高的话(大于了角色飞行高度),角色就会飞不过去,而穿进了墙中。 今天修改后的效果看图: ![](https://img-blog.csdn.net/20171115231531297?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3BpbnNjcmV3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center) 先说一下实现的原理:就是在飞行角色的下面加两个子Point,一直发射射线来作为角色的眼睛。 ![](https://img-blog.csdn.net/20171115231720435?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3BpbnNjcmV3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast) 下面是控制角色的代码:
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;
Vector3 direct = transform.GetChild
(0).position - transform.GetChild(1).position;
if (Physics.Raycast(transform.GetChild
(1).position, direct, out hit))
{
Vector3 newpos = new Vector3
(transform.position.x, hit.point.y + _Height,
transform.position.z);
transform.position = Vector3.MoveTowards(transform.position, newpos, Time.deltaTime * 40); //这里加入了差值
}
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:
transform.LookAt(new Vector3(hit.point.x, transform.position.y, hit.point.z));
desPos = hit.point;
flyBool = true;
break;
}
}
}
}
}
|