以下代码为示例帮助,您可能需要根据自己的需要进行调整和优化。
首先,创建一个PlayerController脚本,用于控制玩家的移动和攻击:
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public float attackThreshold = 0.5f;
public float[] attackDelays;
public string[] attackTriggers;
private Rigidbody rb;
private Animator animator;
private void Start()
{
rb = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
}
private void Update()
{
float moveX = Input.GetAxis("Horizontal");
float moveZ = Input.GetAxis("Vertical");
Vector3 moveDirection = new Vector3(moveX, 0, moveZ);
rb.velocity = moveDirection * moveSpeed;
if (moveDirection != Vector3.zero)
{
animator.SetBool("IsRunning", true);
}
else
{
animator.SetBool("IsRunning", false);
}
if (Input.GetButtonDown("Fire1"))
{
Attack();
}
}
private void Attack()
{
int attackIndex = Random.Range(0, attackDelays.Length);
if (animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1 > attackThreshold)
{
animator.SetFloat("AttackDelay", attackDelays[attackIndex]);
animator.SetTrigger(attackTriggers[attackIndex]);
}
}
}
然后,创建一个AIController脚本,用于控制AI的移动和随机攻击:
using UnityEngine;
using UnityEngine.AI;
public class AIController : MonoBehaviour
{
public Transform target;
public float moveSpeed = 5f;
public float attackThreshold = 0.5f;
public float[] attackDelays;
public string[] attackTriggers;
public float attackRange = 3f;
public float timeBetweenAttacks = 1f;
private NavMeshAgent agent;
private Animator animator;
private float timer;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
animator = GetComponent<Animator>();
timer = timeBetweenAttacks;
}
private void Update()
{
if (target != null)
{
agent.SetDestination(target.position);
float distanceToTarget = Vector3.Distance(transform.position, target.position);
if (distanceToTarget < attackRange)
{
Attack();
}
else
{
animator.SetBool("IsRunning", true);
}
}
}
private void Attack()
{
agent.velocity = Vector3.zero;
animator.SetBool("IsRunning", false);
timer += Time.deltaTime;
if (timer >= timeBetweenAttacks)
{
timer = 0;
int attackIndex = Random.Range(0, attackDelays.Length);
if (animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1 > attackThreshold)
{
animator.SetFloat("AttackDelay", attackDelays[attackIndex]);
animator.SetTrigger(attackTriggers[attackIndex]);
}
}
}
}
将PlayerController脚本添加到玩家对象上,将AIController脚本添加到AI对象上。分别设置好attackDelays和attackTriggers数组的值。
注意:
- 脚本中的MoveSpeed、attackThreshold、attackDelays、attackTriggers等参数值可以根据需要进行调整。
- 脚本中使用的动画参数名称可能需要与你的Animator中指定的名称一致。