Collision between objects
Last updated
Last updated
When we want to animate objects colliding, we need to consider the geometry of each object, and determine when the object geometry overlaps. For this example, we'll look at collision between an ellipse and a rectangle.
Example Khan Academy Project:
https://www.khanacademy.org/computer-programming/colliding-objects/5192472599134208
The image below shows the geometry for the 2 objects used in this example. We have a ball object and a target object. The ball object is defined by the following:
The target is a rectangle defined by the following:
As seen in the image below, the geometries overlap on the left edge of the rectangle when the following is true: bX + bR > tX //the right edge of the ball (bX + bR) is greater than than the left edge of the target ( tX );
We'll create simple functions to create modular logic for this project. We'll have functions to draw the objects, and an additional function to test for collision between the objects. Collision implies that we have moving objects, so we'll need to have: global variables for position and speed of the objects, since those values will be changing. We will also create variables for the geometry: radius, width, and height of the objects to allow us to determine if we have collision.
In the draw function, we'll check if any keyIsPressed, and then check to see if the current keyCode is UP or DOWN.
//parameters: we need to pass in all object geometry to test for collision
In this example, the ball's animation is that it bounces between the left and right edges of the canvas, it also bounces off the target if collision has occurred. Animation can be controlled using a variable for speed, where the speed is reversed when collisions occur.
In this example, this code is written directly in the draw loop.
Here's the full code for the draw function:
check for keyPressed to change the value of targetY.
check for ball hitting either wall - reverse speed
check for collision with target - reverse speed
update ball's position by adding speed
draw Ball
draw Target