我试图让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);
}
}
我想要"目标"为了真正靠近玩家,所以AI站在玩家固定的变换位置。
编辑:场景是超市,目标是用户。用户正在接近货架,AI正在接近用户。所以我需要他们站在一条线上。
答案 0 :(得分:1)
我可以在您的代码中看到您正在计算目标位置,但是在下一行中,而不是将目标分配给 targetLocation 。你是这样做的:
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;