Using python and pygame I've built a collision detection system according to the instructions in this YouTube tutorial.
This is updated 40 times per second and controls movement and collision detection between some number of "agents", which are circles, each with a radius of 20:
for a in self.agents: dir = a.target - a.pos if dir.length >= 3: dir.length = 3 a.pos = a.pos + dir for a in self.agents: for a2 in self.agents: if a==a2: continue d = a.pos.get_distance(a2.pos) if d<40: overlap = 40 - d dir = a2.pos - a.pos dir.length = overlap/2 a2.pos= a2.pos+dir a.pos= a.pos-dir
This looks and works great, as long as the number of agents is below 100. A higher number of agents will cause the pygame frame rate to drop. I left out some code which increases movement speed and pushback for a selected agent, but I don't think it has any consequence for the issue.
How can I make the code more efficient? For instance, would it help to make it so agents only check the distance of other nearby agents, say within a circle 4X the size of the agent, instead checking the complete list in every iteration of the code. Or is it better to change the method all together?