collisionDetection.py
The Problem
MIT OCW 6.189 A Gentle Introduction to Programming Using Python
Lab 6 Problem 1 – Collision detection of balls
Many games have complex physics engines, and one major function of these engines is to figure out if two objects are colliding. Weirdly-shaped objects are often approximated as balls. In this problem, we will figure out if two balls are colliding.
We will think in 2D to simplify things, though 3D isn’t different conceptually. For calculating collision, we only care about a ball’s position in space and its size. We can store position with its center x-y coordinates, and we can use its radius for size. So a ball is a tupple of (x, y, r).
To figure out if two balls are colliding, we need to compute the distance between their centers, then see if this distance is less than the sum of their radii. If so, they are colliding.
Write a function that takes two balls and computes if they are colliding. Then call the function with two sets of balls. The first set is (0, 0, 1) and (3, 3, 1); these should not be colliding. The second set is (5, 5, 2) and (2, 8, 3); these should be colliding.
The Code
from math import sqrt, pow def balls_collide(ball1, ball2): distance = sqrt(pow((ball1[0] - ball2[0]), 2) + pow((ball1[1] - ball2[1]), 2)) sum_radii = ball1[2] + ball2[2] if distance < sum_radii: return True else: return False print balls_collide((0, 0, 1), (3, 3, 1)) print balls_collide((5, 5, 2), (2, 8, 3))


No trackbacks yet.