Getting Started with Box2D in JavaScript |
Written by David Conrad | ||||
Friday, 20 January 2012 | ||||
Page 3 of 3
The complete page is gathered in one place to make it easy for you to copy and paste is: <!DOCTYPE html> Something to stop the fallSo far this isn't very impressive. Let's add a fixed object so that our falling circle has something to bounce on. The construction follows the standard pattern - create a body definition, create a fixture definition and use these to create a body and its fixture: bodyDef.type = b2Body.b2_staticBody; In this case, the only real difference is that we are defining the shape to be a rectangle 20 meters long and 0.4 meters thick. Note that we specify the half-width and half-height in the function call. If you add this to the program just before the end then you will see the ball fall from the "sky" and bounce a few times on the "ground".
Make sure that you understand what is going on. Try changing the restitution to see how it affects the way the ball bounces. You can also try giving the body an initial velocity: var body=world.CreateBody(bodyDef); Now you will see it move sideways bounce and then move off to the left. Notice that the "ball" picks up rotational motion from the collisions as it would in real life. You can also add some side walls to constrain the circle to stay withing a region:
bodyDef.position.x = 0.2; Now you can experiment with giving the ball different initial velocities and see how it bounces. You might also like to add multiple copies of the ball with different random velocities.
You can download the complete program from the CodeBin (note you have to register first). Next Time: More complex bodies
Comments
or email your comment to: comments@i-programmer.info
To be informed about new articles on I Programmer, subscribe to the RSS feed, follow us on Google+, Twitter, Linkedin or Facebook or sign up for our weekly newsletter.
|
||||
Last Updated ( Thursday, 05 January 2017 ) |