我正在努力创造一个" flock" " boids"并且在最初创建boids期间,不得在障碍物上创建它们。然而,它们仍然必须随机创建,障碍也是如此。
所以我随机创建了它们,然后检查它们的位置并在需要时更正它们。这似乎在大多数情况下起作用,但我认为发生的事情是,如果将Boid 1放置在障碍物1上,它会从障碍物1移开,但是它可能会落在障碍物2上。当它被移动时,它可能被移回到障碍物2上。障碍物1,不再检查。我怎样才能阻止这种情况发生?
以下是创建代码:
def create_boids(self):
for boid in range(self.flock_number): # add the specified number of boids to our flock within our screen's region.
self.boids.append(Boid(random.randint(self.region[0], self.region[2]), random.randint(self.region[1], self.region[3])))
for boid in self.boids: # adjust our boids so they are not created on top of an obstacle and are within our screen's region.
for obstacle in self.obstacles:
while colliding(boid.pos[0], boid.pos[1], boid.radius, obstacle[0][0], obstacle[0][1], obstacle[1]):
boid.pos[0] = random.randint(self.region[0], self.region[2])
boid.pos[1] = random.randint(self.region[1], self.region[3])
self.region = (x, y, width, height)
obstacle in self.obstacles = ((x, y), radius)
这也是碰撞检查。
def colliding(c1x, c1y, c1r, c2x, c2y, c2r):
if (int(c1x) - int(c2x)) ** 2 + (int(c1y) - int(c2y)) ** 2 <= (int(c1r) + int(c2r)) ** 2:
return True
return False
我不确定在这里尝试什么。感谢您的帮助!
答案 0 :(得分:1)
有一个功能可以检查boid是否与任何障碍物发生碰撞......并且只要它保持选择新位置:
def is_boid_colliding_with_obstacles(self, boid):
return any(colliding(boid.pos[0], boid.pos[1], boid.radius,
obstacle[0][0], obstacle[0][1], obstacle[1])
for obstacle in self.obstacles)
def create_boids(self):
for boid in range(self.flock_number): # add the specified number of boids to our flock within our screen's region.
self.boids.append(Boid(random.randint(self.region[0], self.region[2]), random.randint(self.region[1], self.region[3])))
for boid in self.boids: # adjust our boids so they are not created on top of an obstacle and are within our screen's region.
while self.is_boid_colliding_with_obstacles(boid):
boid.pos[0] = random.randint(self.region[0], self.region[2])
boid.pos[1] = random.randint(self.region[1], self.region[3])
或者,更好的是,首先只生成有效的boids:
def is_boid_colliding_with_obstacles(self, boid):
return any(colliding(boid.pos[0], boid.pos[1], boid.radius,
obstacle[0][0], obstacle[0][1], obstacle[1])
for obstacle in self.obstacles)
def create_boid(self):
while True:
boid = Boid(random.randint(self.region[0], self.region[2]),
random.randint(self.region[1], self.region[3]))
if not self.is_boid_colliding_with_obstacles(boid):
return boid
def create_boids(self):
self.boids.extend(self.create_boid() for _ in range(self.flock_number))