1.敌人巡逻
通过在场景中设置任意数量空物体作为巡逻的点位,点与点之间的连线作为巡航路线;给敌人添加Nav Mesh Agent组件,通过SetDestination/destination将点位设置为目的地。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class _3_6 : MonoBehaviour
{
public Transform[] waypoints;//场景中巡逻的点位
int index = 0;
NavMeshAgent nav;
float timer = 0;
float waitTimer =3f;//到达某一点停止等待时间
void Start () {
nav = GetComponent<NavMeshAgent>();
nav.destination = waypoints[index].position;
}
void Update () {
if (nav.remainingDistance < 0.5f)//(距离终点)剩余移动距离
{
timer += Time.deltaTime;
if (timer >= waitTimer)
{
index++;
index %= 4;//场景中4个点位,对4取余获取点位对应的下标
timer = 0;
Debug.Log(index);
nav.destination = waypoints[index].position;
}
}
}
}
2.攻击与追踪
通过判断与玩家之间的距离,决定是否终止巡航
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class _3_6 : MonoBehaviour
{
public GameObject player;
public Transform[] waypoints;//场景中巡逻的点位
int index = 0;
NavMeshAgent nav;
float timer = 0;
float waitTimer =3f;//到达某一点停止等待时间
void Start () {
nav = GetComponent<NavMeshAgent>();
nav.destination = waypoints[index].position;
}
void Update () {
Vector3 playerPos = player.transform.position;
float distance = Vector3.Distance(transform.position, playerPos);
if (distance <= 2f)
{
//停止巡逻 攻击玩家
agent.ResetPath();
}
else if (distance <= 5f)
{
//追踪玩家
nav.destination = player.transform.position;
//存在疑问 若属于追踪范围,敌人看向LookAt玩家并向前移动transform.forward行不通
}
else
{
//巡逻
}
}
}
3.摄像机跟随
公式:pos= player.position + Vector3.up * distanceUp - player.forward * distanceAway;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class _3_6 : MonoBehaviour
{
public float distanceAway=1.7f;
public float distanceUp=1.3f;
public float smooth=2f;
Vector3 pos; //摄像机准备照射的位置
Transform player; //主角的位置
void Start(){
player= GameObject.FindWithTag ("Player").transform;
}
void Update ()
{
pos= player.position + Vector3.up * distanceUp - player.forward * distanceAway;
//差值
transform.position=Vector3.Lerp(transform.position, pos, Time.deltaTime * smooth);
//摄像机朝向玩家
transform.LookAt(player);
//计算出摄像机面向玩家角色的旋转角度
//Quaternion targetRotation = Quaternion.LookRotation(player.position - transform.position);
//设置摄像机旋转
//transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
}
}
4.相机跟随鼠标旋转
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class _3_6 : MonoBehaviour
{
float speed = 50;
void Update ()
{
float x = Input.GetAxis("Mouse X");
float y = Input.GetAxis("Mouse Y");
float z = Input.GetAxis("Mouse ScrollWheel");
if (z < 0)
{
if (Camera.main.fieldOfView < 90)
{
Camera.main.fieldOfView += 2;
}
}
if (z > 0)
{
if (Camera.main.fieldOfView > 30)
{
Camera.main.fieldOfView -= 2;
}
}
if(x!=0 || y != 0)
{
x *= speed * Time.deltaTime;//鼠标横向移动变化值
transform.Rotate(0, x, 0);//摄像机随着鼠标在x轴的变化绕y轴旋转
y *= speed * Time.deltaTime;//鼠标纵向移动变化值
transform.Rotate(-y, 0, 0);//摄像机随着鼠标在y轴的变化绕x轴旋转
}
}
}
5.画中画
添加副摄像机,调整HWXY圈定视野在屏幕中的位置,调整视野范围放大缩小