首先创建一个烘焙过后的场景,这个比较容易,简单说一下
创建需要的场景,我这里是测试
设置为Static类型
点击 Bake
接下来给Player挂脚本 MoveCube
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class MoveCube : MonoBehaviour {
NavMeshAgent m_nav;
LineRenderer m_line;
Ray ray;
RaycastHit hit;
Vector3 vector3;
private void Awake()
{
m_nav = GetComponent<NavMeshAgent>();
m_line = GetComponent<LineRenderer>();
m_line.enabled = false;
}
private void Start()
{
StartCoroutine(OnMouseDown());
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
//激活线性渲染组件
m_line.enabled = true;
ray = Camera.main.ScreenPointToRay(Input.mousePosition);//从摄像机发射射线到屏幕,并返回这条射线。
if (Physics.Raycast(ray, out hit))
{
vector3 = hit.point;
NavMeshPath path = new NavMeshPath();//设置路径的点
m_nav.CalculatePath(vector3, path);//路径,导航
//m_line.SetVertexCount(path.corners.Length); 过时的,API查找
m_line.positionCount = path.corners.Length;//线性渲染设置拐点数。数组类型的
m_line.SetPositions(path.corners);
//m_nav.SetDestination(vector3);
}
}
}
IEnumerator OnMouseDown()
{
//将物体由世界坐标系转换为屏幕坐标系
Vector3 screenSpace = Camera.main.WorldToScreenPoint(transform.position);//三维物体坐标转屏幕坐标
//完成两个步骤 1.由于鼠标的坐标系是2维,需要转换成3维的世界坐标系
// // 2.只有3维坐标情况下才能来计算鼠标位置与物理的距离,offset即是距离
//将鼠标屏幕坐标转为三维坐标,再算出物体位置与鼠标之间的距离
Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
while (Input.GetMouseButton(0))
{
//得到现在鼠标的2维坐标系位置
Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
//将当前鼠标的2维位置转换成3维位置,再加上鼠标的移动量
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
//curPosition就是物体应该的移动向量赋给transform的position属性
transform.position = curPosition;
yield return new WaitForFixedUpdate(); //这个很重要,循环执行
}
}
}
扫描二维码关注公众号,回复:
4867774 查看本文章
接下来给Player添加组件。
这里LineRenderer在设置的时候有个坑,默认设置LineRenderer----->Positions
这样的话,在场景运行时,不会显示LineRenderer初始的那小段
运行。
效果如下
这里有一个问题,就是再次移动Plyer的时候,射线会穿透Plyer在地面上留下一个点,如下图:
解决办法:有待解决,各位大佬,有解决方案留下你的思路,谢谢
等我想出来办法在来更新