BK.Physics 物理引擎

BK.Physics 通过为刚性物体赋予真实的物理属性的方式来计算运动、旋转和碰撞反映。

通过 BK.Physics 模拟重力使星星下落:

 1.1.3.8.物理引擎  - 图1

  1. var space = new BK.Physics.Space({"x":0,"y":-100}, 5)
  2. BK.Director.attachSpace(space)
  3. var screenScale = BK.Director.screenScale;
  4. var tris = [{x: -20 * screenScale, y: -20 * screenScale}, {x: 0, y: 15 * screenScale}, {x: 20 * screenScale, y: -20 * screenScale}];
  5. var staticBody = space.staticBody;
  6. for (var i = 0; i < 9; i++) {
  7. for (var j = 0; j < 6; j++) {
  8. var stagger = (j % 2) * 40;
  9. var offset = {x: (i * 80 + stagger) * screenScale, y: (j * 100 - 50) * screenScale};
  10. var shape = new BK.Physics.PolygonShape(staticBody, tris, {a:1, b:0, c:0, d:1, tx: offset.x, ty: offset.y}, 0);
  11. space.addShape(shape);
  12. shape.friction = 1.0;
  13. shape.elasticity = 1.0;
  14. }
  15. }
  16. var verts = new Array(5);
  17. var minX = 10000, maxX = 0, minY = 10000, maxY = 0;
  18. for (var i = 0; i < 5; i++) {
  19. var angle = -2.0 * 3.1415926 * i / 5;
  20. verts[i] = {x: 10 * Math.cos(angle) * screenScale, y: 10 * Math.sin(angle) * screenScale};
  21. if (minX > verts[i].x)
  22. minX = verts[i].x;
  23. if (minY > verts[i].y)
  24. minY = verts[i].y;
  25. if (maxX < verts[i].x)
  26. maxX = verts[i].x;
  27. if (maxY < verts[i].y)
  28. maxY = verts[i].y;
  29. }
  30. for (var i = 0; i < 100; i++) {
  31. var mass = 10;
  32. var moment = BK.Physics.momentForPolygon(mass, verts, {x:0,y:0}, 0);
  33. var body = new BK.Physics.Body(0, mass, moment, {"x":0,"y":0});
  34. var x = Math.random() * BK.Director.screenPixelSize.width;
  35. body.position = {x: x, y: BK.Director.screenPixelSize.height, z: 0};
  36. space.addBody(body);
  37. var shape = new BK.Physics.PolygonShape(body, verts, {a:1,b:0,c:0,d:1,tx:0,ty:0}, 0);
  38. shape.friction = 0.4;
  39. shape.elasticity = 0;
  40. space.addShape(shape);
  41. var centroid = body.centerOfGravity;
  42. var backTex = new BK.Texture('GameRes://resource/texture/star.png');
  43. var sp = new BK.Sprite(maxX - minX, maxY - minY, backTex,0,1,1,1);
  44. sp.anchor = {x: 0.5, y: 0.5};
  45. sp.attachComponent(body);
  46. sp.position = {x: x, y: BK.Director.screenPixelSize.height - 100, z: 0};
  47. BK.Director.root.addChild(sp);
  48. }
  49. //打开测试包围盒
  50. BK.Physics.setSwitch(true);

接口说明:BK.Physics 物理引擎

示例代码:script/demo/physics/physics_demo.js

原文: https://hudong.qq.com/docs/engine/engine/native/func/funcs/physics.html