我在实现Conrad Parker的boids伪代码时遇到了问题。
我正在执行规则1,规则2和规则3。问题是,只要rule3处于活动状态(即我下面代码中的matchSpeed),生物就会冲向世界的中心(0,0,0),然后聚集在那里。无论他们从哪里开始,都会发生这种情况。
但是当rule3不运行时,生物就会像预期的那样聚集和漂移。我做错了什么?
我的代码是在Scala和我使用的jMonkeyEngine,但我怀疑这个问题是一个普遍的。
val sepDistance = 10f
val clumpFactor = 100f
val avoidFactor = 3f
val alignFactor = 800f
val speedLimit = 2f
def moveAgents(target: Node)
{
agents.foreach(a => {
a.velocity.addLocal(clump(a)) //rule1
a.velocity.addLocal(keepAway(a)) //rule2
a.velocity.addLocal(matchSpeed(a)) //rule3
a.velocity = limitSpeed(a.velocity)
a.move(a.velocity)
})
}
def clump (a: Agent): Vector3f = // rule1
{
val centre = Vector3f.ZERO.clone
for (oA <- agents if oA != a) yield
centre.addLocal(oA.position)
centre.divideLocal(agents.length.toFloat - 1f)
centre.subtractLocal(a.position)
centre.divideLocal(clumpFactor)
return centre
}
def keepAway (a: Agent): Vector3f = // rule2
{
val keepAway = Vector3f.ZERO.clone
for (oA <- agents if oA != a) {
if (Math.abs(oA.position.distance(a.position)) < sepDistance)
keepAway.subtractLocal(oA.position.subtract(a.position))
}
return keepAway.divide(avoidFactor)
}
def matchSpeed (a: Agent): Vector3f = // rule3
{
val matchSpeed = Vector3f.ZERO.clone
for (oA <- agents if oA != a)
matchSpeed.addLocal(oA.velocity)
matchSpeed.divideLocal(agents.length.toFloat - 1f)
matchSpeed.subtractLocal(a.position)
matchSpeed.divideLocal(alignFactor)
return matchSpeed
}
问题是matchSpeed方法从平均速度中减去焦点体的位置,而不是它的速度。
:
matchSpeed.subtractLocal(a.position)
应:matchSpeed.subtractLocal(a.velocity)