Unity2D 如何让 Ai 随机运行方向



YouTube上有一些教程,但我认为这不是正确的事情,为什么? 是的,AI 确实以随机方向运行,但动画不会。 甚至 AI 也在移动其静止的空闲动画。是否有人有源代码或想法来使其按应有的方式工作?请帮助我,我已经在这个东西上呆了一个星期了。 我已经尽我所能,但一切都失败了,请帮我这个我求你。我只有 1 天的时间来完成 IM 为我们学校期中考试创建的基本游戏。我不想失败T_T

public float moveSpeed;
private Rigidbody2D myRigidbody;
public bool isWalking;
public float walkTime;
private float walkCounter;
public float waitTime;
private float waitCounter;
private int walkDirection;

public Animator animator;
void Start()
{
animator = GetComponent<Animator>();
animator.SetBool("IsRunning", true);
myRigidbody = GetComponent<Rigidbody2D>();
waitCounter = waitTime;
walkCounter = walkTime;
ChooseDirection();
}
void Update()
{
animator.SetBool("IsRunning", isWalking);
if (isWalking)
{
walkCounter -= Time.deltaTime;
switch (walkDirection)
{
case 0:
myRigidbody.velocity = new Vector2(0, moveSpeed);
break;
case 1:
myRigidbody.velocity = new Vector2(moveSpeed, 0);
break;
case 2:
myRigidbody.velocity = new Vector2(0, -moveSpeed);
break;
case 3:
myRigidbody.velocity = new Vector2(-moveSpeed, 0);
break;
}
if (walkCounter < 0)
{
isWalking = false;
waitCounter = waitTime;
}
}
else
{
waitCounter -= Time.deltaTime;
myRigidbody.velocity = Vector2.zero;
if (waitCounter < 0)
{
ChooseDirection();
}
}
}
public void ChooseDirection()
{
walkDirection = Random.Range(0, 4);
isWalking = true;
walkCounter = walkTime;
}
}

在"开始"屏幕上获取动画师引用

public Animator animator;
void Start()
{
//Assuming that the Animator is attached to the same Game Object as this script
animator = GetComponent<Animator>();
}

创建一个参数(在本例中为名为"IsRunning"的布尔值(,并在开始运行时设置它

animator.SetBool("IsRunning", true);

在您的情况下,您可能希望在"isWalking"变量更改时更新状态,因此在"更新"中

animator.SetBool("IsRunning", isWalking);

最新更新