Simple Box2D example


/ Published in: JavaScript
Save to your folder(s)

A Titanium Appcelerator example for implementing Box2D module


Copy this code and paste it in your HTML
  1. var window = Ti.UI.createWindow();
  2. var view = Ti.UI.createView();
  3. window.add(view);
  4. window.open();
  5.  
  6. // load the module
  7. var Box2D = require('ti.box2d');
  8.  
  9. // create the world, using view as the surface
  10. var world = Box2D.createWorld(view);
  11.  
  12. // create a block
  13. var redBlock = Ti.UI.createView({
  14. backgroundColor: "red",
  15. width: 50,
  16. height: 50,
  17. top: 0
  18. });
  19.  
  20. var blueBall = Ti.UI.createView({
  21. backgroundColor: "blue",
  22. borderRadius: 15,
  23. width: 30,
  24. height: 30,
  25. top: 100
  26. });
  27.  
  28. // add the block body to the world
  29. var redBodyRef = world.addBody(redBlock, {
  30. density: 12.0,
  31. friction: 0.3,
  32. restitution: 0.4,
  33. type: "dynamic"
  34. });
  35.  
  36. // add the ball body to the world
  37. var blueBodyRef = world.addBody(blueBall, {
  38. radius: 15,
  39. density: 12.0,
  40. friction: 0.3,
  41. restitution: 0.4,
  42. type: "dynamic"
  43. });
  44.  
  45. Ti.Gesture.addEventListener('orientationchange', function(e) {
  46. if (e.orientation == Titanium.UI.LANDSCAPE<em>LEFT) {
  47. world.setGravity(9.91, 0);
  48. } else if (e.orientation == Titanium.UI.LANDSCAPE</em>RIGHT) {
  49. world.setGravity(-9.91, 0);
  50. } else if (e.orientation == Titanium.UI.UPSIDE_PORTRAIT) {
  51. world.setGravity(0, 9.91);
  52. } else if (e.orientation == Titanium.UI.PORTRAIT) {
  53. world.setGravity(0, -9.91);
  54. }
  55. });
  56.  
  57. world.addEventListener("collision", function(e) {
  58. if ((e.a == redBodyRef || e.b == redBodyRef) &amp;&amp; e.phase == "begin") {
  59. Ti.API.info("the red block collided with something");
  60. Ti.API.info(JSON.stringify(e));
  61. Ti.Media.vibrate();
  62. }
  63. });
  64.  
  65. // start the world
  66. world.start();

URL: http://lancespellman.com/2011/12/20/cool-box2d-stuff-with-appcelerator-titanium/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.