WiiLab Example Code - BouncingBall: getYVel
Note: MATLAB R2007a or greater is required for this code to run correctly.
Annotations
Called by the main program file each time through the while loop to update the ball's vertical velocity and account for gravity. Special case: When the ball hits the lowest point in the window (the "ground"), the direction of y-velocity changes and an elasticity of 80% is accounted for, decreasing the maximum height of the ball's next bounce.
Raw Source Code
The source code is also available as a .m file download at the bottom of the page.
function getYVel(y)
% usage: getYVel(yPosition)
% purpose: calculate the new Y-velocity so the ball can be moved
% "accurately" (a relative term) in the BouncingBall program
global yVel;
% if the ball has hit the bottom of the screen
if (y <= 10)
% change the direction of y-velocity and account for elasticity
yVel = -0.8*yVel;
% if ball is moving just fine
else
% make it either fall more quickly or climb more slowly, due to gravity
yVel = yVel - 0.98;
end %if
end