我在实现Conrad Parker's boids pseudocode时遇到了问题。
我正在实现rule1、rule2和rule3。问题是,只要rule3是活动的(即我下面代码中的matchSpeed ),boids就会冲到世界的中心(0,0,0),然后聚集在那个点周围。无论它们在世界上从哪里开始,都会发生这种情况。
但是当rule3没有运行时,boid就会像预期的那样聚集和漂移。我做错了什么?
我的代码是用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
}发布于 2013-06-04 17:42:44
问题是matchSpeed方法从平均速度中减去了震源体的位置,而不是它的速度。
所以:
matchSpeed.subtractLocal(a.position)应该是:
matchSpeed.subtractLocal(a.velocity)https://stackoverflow.com/questions/16913524
复制相似问题