Make a Ball Bounce off Walls
In fact, if we can master this simple concept we will have some fundamental tools for game development and trigonometry.
Let's take a look at a bit of code to see how this works.
//move the ball
ball.x += Math.cos(ball.angle) * ball.speed;
ball.y += Math.sin(ball.angle) * ball.speed;
if(ball.x - ball.radius < 0) // ball hits left wall
{
ball.x = ball.radius;
ball.angle = Math.PI - ball.angle;
}
else if(ball.x + ball.radius > c.width)// ball hits right wall
{
ball.x = c.width - ball.radius;
ball.angle = Math.PI - ball.angle;
}
if(ball.y < ball.radius)// ball hits top wall
{
ball.y = ball.radius;
ball.angle = (Math.PI * 2) - ball.angle;
}
else if(ball.y + ball.radius > c.height)// ball hits bottom wall
{
ball.y = c.height - ball.radius;
ball.angle = (Math.PI * 2) - ball.angle;
}
How Do We Move the Ball
The fundamentals of game programming and
trigonometry are the functions cos and sin (cosine and sine).
Cos relates to horizontal movement and sin relates to vertical movement.
Taking the cosine or sine of our angle gives us a number between -1 and 1.
Based on the numbers we get we know how far to go in each direction.
For example, if the cos of our angle gives us -1 we are going fully to the right, if it gives us 1 we are going fully to the right, if it gives us 0 we have no horizontal movement (we are going straight up or down).
The same logic applies for sin except it handles the vertical movement.
Taking the cos and sin of our angle give us our
unit vector,
we then multiply the results by our desired speed.
How Do We Decide the Angle
When the ball hits a wall we calculate our new rebound angle based on the angle the ball is moving and the angle of the wall.
In our case it is easier because we know all of our walls are either horizontal or vertical (no diagonal walls).
A wall is 180 degrees (or PI in radians, but degrees are usually easier to work with),
if the angle between the ball and wall is 20 degrees, the reflection should be (180 - 20) this will create a reflection and cause the ball to bounce at an equal but opposite (reflected) angle.
Resources
- Elements of Programming
- Beginning Math and Physics for Game Programmers
- Euclid's Elements (The Thirteen Books)
- From Mathematics to Generic Programming
- Data-oriented design: software engineering for limited resources and short schedules
- Design of Design, The: Essays from a Computer Scientist
- Mythical Man-Month, The: Essays on Software Engineering, Anniversary Edition
- More Effective C++: 35 New Ways to Improve Your Programs and Designs
- Mathematics for Machine Learning
- The Pragmatic Programmer: Your Journey To Mastery, 20th Anniversary Edition (2nd Edition)
- Game Programming Patterns
- Schaum's Outline of Essential Computer Mathematics 1st Edition
- Mathematics for the Nonmathematician
- All recommended resources