This site requires JavaScript, please enable it in your browser!
Greenfoot back
M.Hussain
M.Hussain wrote ...

2014/8/15

Code for a bouncing ball

M.Hussain M.Hussain

2014/8/15

#
Can any one help me with a code for bouncing a ball
danpost danpost

2014/8/15

#
All you need is an instance int field to track the vertical speed of the ball. Have the act method increase its value each act cycle to represent acceleration due to gravity. Add the speed value to the vertical location of the ball each act cycle to represent movement. Check for the ball hitting the ground and when needed negate the speed to represent a bounce. You can also add a slight amount to the speed value to represent drag or energy loss during bounce.
M.Hussain M.Hussain

2014/8/16

#
Can u give the code....
danpost danpost

2014/8/16

#
You need to provide what code you have so far (at least as far as the ball and its ground/object detection). However, for gravity:
// instance field
int vSpeed; // to track the speed of the ball

// in act method
vSpeed++; // applying gravity
setLoation(getX(), getY()+vSpeed); // moving vertically
// check for collision/bounce (above and below -- hint: mind sign of 'vSpeed')
You need to login to post a reply.