如何让敌人在距离玩家一定距离时停止,而不是直接靠近?我想创建一个远程单位。我可以处理敌人的攻击,只是不想让敌人直接靠近玩家。我的敌人上有一个使用AStar路径查找包的自定义AI脚本 –
Transform target; public float speed = 200f; public float nextWaypointDistance = 3f; public Transform enemyGFX; Path path; int currentWaypoint = 0; bool reachedEnd = false; Seeker seeker; Rigidbody2D rb; void Start() { seeker = GetComponent<Seeker>(); rb = GetComponent<Rigidbody2D>(); target = GameObject.Find("Player").transform; InvokeRepeating("UpdatePath", 0.0f, 0.5f); } void UpdatePath() { if(seeker.IsDone()) { seeker.StartPath(rb.position, target.position, OnPathComplete); } } void OnPathComplete(Path p) { if(!p.error) { path = p; currentWaypoint = 0; } } void FixedUpdate() { if (path == null) return; if(currentWaypoint >= path.vectorPath.Count) { reachedEnd = true; return; } else { reachedEnd = false; } Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized; Vector2 force = direction * speed * Time.deltaTime; rb.AddForce(force); float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]); if(distance < nextWaypointDistance) currentWaypoint++; }}
非常感谢所有帮助!
回答:
正确的方法不是寻找特定的节点,而是寻找目标周围一定距离内的任何节点,或者是与目标有一定距离且有直接视线的任何节点。
看起来AStar路径查找库应该有这样的功能。例如,有一个GetNearest重载,它接受一个可能有效的约束。或者是maxNearestNodeDistance
字段。但我不熟悉这个库,所以很难提供具体的建议。
另一种选择是自己编写实现。这并不简单,但也不算太复杂,有很多资源解释像A*这样的算法。你可能无法达到商业库的功能齐全性,但你可能只需要相当简单的功能。这也可能作为一个学习练习,帮助你更好地了解AI和路径查找的工作原理。