赞
踩
这篇博客主要记录一下敌人自动寻路以及点击地面移动的相关知识点
简单的自动寻路功能,新增了可以去多个位置巡逻
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class _nav : MonoBehaviour { private NavMeshAgent foxNav; public Transform playerTrans; public Transform[] transforms; float time = 0; int i = 0; void Start() { foxNav = GetComponent<NavMeshAgent>(); foxNav.SetDestination(transforms[i].position); } // Update is called once per frame void Update() { //自动寻路 // foxNav.SetDestination(playerTrans.position); //若距离很小,就设为到达 if (Vector3.Distance(foxNav.nextPosition, foxNav.destination) < 0.2f) { this.transform.position = foxNav.nextPosition; time += Time.deltaTime; if (time > 3) { time = 0; foxNav.SetDestination(transforms[(i++)%transforms.Length].position); } } } }
用鼠标点击地面,游戏对象便会走到相应位置
//摄像机跟随的设置
public class _cameraPos : MonoBehaviour { public Transform Player; Vector3 cameraPos; void Start() { //固定三维向量差 cameraPos = transform.position - Player.transform.position; } // Update is called once per frame void Update() { transform.position = Player.transform.position + cameraPos; cameraPos = transform.position - Player.transform.position; // transform.position = new Vector3(Player.transform.position.x + cameraPos.x, Player.transform.position.y + cameraPos.y, Player.transform.position.z + cameraPos.z); } }
具体代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class _Game2PlayerMove : MonoBehaviour { private NavMeshAgent playerNav; void Start() { playerNav = GetComponent<NavMeshAgent>(); } // Update is called once per frame void Update() { //通过鼠标点击人物移动 if (Input.GetMouseButtonDown(0)) { //从鼠标位置发射一条射线 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; //如果射线检测到物体/碰撞盒 if (Physics.Raycast(ray, out hit)) { playerNav.SetDestination(hit.point); //物体下一步的位置 // Debug.Log(playerNav.nextPosition + "nextPosition"); //物体终点的位置 //Debug.Log(playerNav.destination + "destination"); } } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。