【问题标题】:Ai spins all the time when collision occurs碰撞发生时ai一直在旋转
【发布时间】:2017-09-01 19:29:48
【问题描述】:

有一个简单的 AI,它会在玩家处于范围内时跟随玩家,并在 AI 不在玩家范围内时随机移动它。当 AI 撞到墙并超出玩家范围时,它开始一直旋转。无法弄清楚为什么它一直这样做。

我可能错过了一件简单的事情...... 非常感谢您的帮助。

void Update()
{
    Target = GameObject.FindGameObjectWithTag("Player");

    if (Vector3.Distance(Target.transform.position, transform.position) < 25)
    {
        followPlayer();
    }
    else
    {
        randomMovement();
    }

}

public void followPlayer()
{

    if (Vector3.Distance(transform.position, Target.transform.position) >= MinDist)
    {

        transform.position += transform.forward * MoveSpeed * Time.deltaTime;
        transform.LookAt(Target.transform);


        if (Vector3.Distance(transform.position, Target.transform.position) <= MaxDist)
        {
        }

    }
    else
    {

    }

}

public void randomMovement()
{
    transform.position += transform.forward * MoveSpeed * Time.deltaTime;
    transform.Rotate(RandomDirection * Time.deltaTime * 10.0f);

}

void OnCollisionEnter(Collision col)
{
    bool hasTurned = false;

    if (col.transform.gameObject.name != "Terrain")
    {
        if(hasTurned == false)
        {
            RandomDirection = new Vector3(0, Mathf.Sin(TimeBetween) * (RotationRange / 2) + OriginalDirection, 0);
            randomMovement();
            hasTurned = true;
        }
        else
        {
            randomMovement();
            hasTurned = false;
        }


        Debug.Log("Hit");
    }

【问题讨论】:

  • 你的 AI 实体上是否有一个刚体?这可能是碰撞后导致旋转的原因。如果是这样,请尝试冻结旋转。看看:docs.unity3d.com/ScriptReference/Rigidbody-freezeRotation.html 也有可能,它看起来像在旋转,因为你它一直与墙壁发生碰撞,因为你选择了一个相当随机的旋转并让它移动,而不是拥有一个“智能”摆脱障碍的方法
  • 是的,这可能是问题的原因!谢谢@TobiasTheel
  • 如果您可以确认,这确实是原因,我会为此创建一个答案:)
  • 很遗憾,没有,仍然在旋转... 在再次检查之前,必须想出一种聪明的方法将玩家移开。 @TobiasTheel
  • 一个相当“愚蠢”的解决方案可能是让 AI 在碰撞时向相反的方向走去。由于您似乎没有使用 PathFinding 它可能是一个临时修复。

标签: c# unity3d vector artificial-intelligence collision-detection


【解决方案1】:

它不断旋转的原因是因为您在 Update() 中不断调用 randomMovement(),它不断地使用 Rotate() 对您的对象应用旋转。听起来您正在尝试做的是让对象每隔几秒钟就漫无目的地游荡。您可以通过在 randomMovement() 上实现 on timer 来做到这一点,这样每隔几秒钟,它就会生成一个新的旋转(类似于您在 onCollision 中的旋转)。下面的例子。

float t = 0;
public void randomMovement()
{
    transform.position += transform.forward * MoveSpeed * Time.deltaTime;

    t += Time.deltaTime;
    if (t > 3f) // set to a new rotation every 3 seconds.
    {
        t = 0; // reset timer
        RandomDirection = new Vector3(0, Random.Range(0f, 360f), 0); // turn towards random direction

        transform.Rotate(RandomDirection);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多