0

What does a simple video game collision detection look like in code

What does a simple video game collision detection look like in code in C, C++, C#, Java and Python??

19th Sep 2019, 12:07 PM
IDGam3r
IDGam3r - avatar
3 Answers
0
Create a hit box, which simply might be a rectangle. Then use conditions, to test against collision ( smaller or bigger than the rectangle)
19th Sep 2019, 12:48 PM
Loeschzwerg
0
Collision is easiest to check for circles. If you know the middle of the circles and circle ranges you can check collision of 2 circles by the dot operator. In maths it would look like this: √(∆x² + ∆y²) In Python it could look like this: def dot(pos1, pos2): return ((pos2[0] - pos1[0])**2 + (pos2[1] - pos1[1])**2)**0.5 def collide_circles(self, other): distance = dot(self.pos, other.pos) return distance > self.range + other.range
19th Sep 2019, 12:53 PM
Seb TheS
Seb TheS - avatar
0
For rectangles it is more complicated, but if we assume that retangles can not be rotated it can be easily done by making list of each side of the rectangle. Let's assume rectangle position is top-left angle position. def collide_dot_and_rect(dot, rect): return any(0 < dot[i] - rect.pos[i] < rect.size[i] for i in range(2)) def collides_rect(self, other): positions = (self.pos, (self.pos[0], self.pos[1] + self.size[1]), (self.pos[0] + self.size[0], self.pos[1] + self.size[1]), (self.pos[0] + self.size[0], self.pos[1])) return any(collide_dot_and_rect(position, other) for position in positions) Sorry for unreadability.
19th Sep 2019, 1:05 PM
Seb TheS
Seb TheS - avatar