当 AI 到达目标时转换到固定位置

translate to a fixed position when AI reach target

我正在尝试让 AI 代理站在实际目标旁边的固定位置。

有人要求我分享代码。这是我在网上找到的最终状态机的一个脚本。

这是 C# 中的完整状态代码:

public class GoToSpecificPoint : IShopperState
{
private readonly StatePatternShopper shopper;
private readonly float distanceFromShelfModifier = 1.5f;

private int nextWayPoint;

private bool enRoute = false;
private bool waitingForPlayer = false;

private float initialPlayerDistanceFromShelf = 1f;
private Transform playerTransform;
private Vector3 targetLocation;

private bool inPlayerSpace = false;
private bool alreadyPicked = false;

public GoToSpecificPoint(StatePatternShopper statePatternShopper)
{
    shopper = statePatternShopper;
}

public void UpdateState()
{
    if (PlayerStillAtShelf())
    {
        enRoute = false;
        waitingForPlayer = true;
    }

    else if (waitingForPlayer && !PlayerStillAtShelf())
    {
        waitingForPlayer = false;
        ToReachPointState();
    }

    }

private bool PlayerStillAtShelf()
{
    float dist;

    if ((dist = Vector3.Distance(targetLocation, playerTransform.position)) > (initialPlayerDistanceFromShelf * distanceFromShelfModifier))
    {
        return false;
    }

    return true;
}

public void SpecificPoint(Vector3 target, Transform player)
{
    alreadyPicked = false;
    enRoute = true;
    playerTransform = player;
    target = new Vector3(player.position.x, 0, player.position.z - 1);
    targetLocation = target;

    initialPlayerDistanceFromShelf = Vector3.Distance(targetLocation, playerTransform.position);

    shopper.meshRendererFlag.material.color = Color.red;
    shopper.navMeshAgent.destination = targetLocation;
    shopper.navMeshAgent.Resume();

    shopper.animator.SetBool("Walk", true);
}

}

我想让 "target" 离玩家很近,所以 AI 站在玩家固定的位置。

EDIT:场景是超市,目标是用户。用户在靠近货架,AI也在靠近用户。所以我需要他们站成一排。

我可以在您的代码中看到您正在计算 target 位置,但在下一行而不是将 target 分配给目标位置。你在做这个:

target = new Vector3 (player.position.x, 0, player.position.z - 1);
target = targetLocation; // you are overriding the above calculated target

为此更改行:

targetLocation = target;

因为您在下方指定了 targetLocation。这里:

shopper.navMeshAgent.destination = targetLocation;