Recently I started learning OOP and decided to create a small game in Python using the arcade library. I decided not to use sprites and their built-in functions. Then I had a problem how to determine whether objects are touching. I wrote the following function:

def get_distance(el1, el2): return ((el1.x - el2.x) ** 2 + (el1.y - el2.y) ** 2) ** 0.5 

In the update method of the MyGame class, I check:

 if get_distance(self.hero, bullet) < 20: self.bullet_list.remove(bullet) 

It all works, but if the bullet hits not exactly the middle of the player, then it does not disappear. Help, how can you make the definition of the contact of objects more accurate? Any complicated formula? ..

PS So I draw a player:

 def draw(self): arcade.draw_circle_filled(self.x, self.y, self.r, self.color) arcade.draw_line(self.x, self.y, self.x+45*self.dx, self.y+45*self.dy, arcade.color.BLACK, 5) 

And this is a bullet:

 def draw(self): arcade.draw_line(self.x, self.y, self.x+9*self.dx, self.y+9*self.dy, self.color, 5) 

1 answer 1

What is 20?

If the object and the bullet are round, then the distance between the centers should be compared with the sum of their radii.

 if get_distance(self.hero, bullet) < self.r + bullet.r: 

For a bullet in the form of a cylinder ("sausages", stadium ), one can consider the distance to the central segment, but the bullet is unlikely to touch the object with the middle.

In the general case, by the way, in order not to miss the exact moment of contact, it is better to calculate this moment in advance, based on the positions and speeds of objects and bullets.

  • And what about square objects? You can, of course, try to fit them in a circle, but here again there will be inaccuracies. By the way, what you wrote in the last paragraph of the answer is also quite interesting. I need such a definition, because in my game there are also bots that periodically shoot at you, but they will never fall if you move all the time. Could you explain more about this definition? Provide a code for a function that will determine where the bot should be fired? Maybe this is another question than what I asked in the title, however ... - Mikhail Muratov
  • With rectangles, you need to use a function that counts the distance from the center of the circle (bullet) to the rectangle's border. By anticipation when shooting - this is really another matter. - MBo pm