OBB碰撞检测

spritejs提供了一个简单的碰撞检测机制,使用的是OBB碰撞检测算法,可以方便地检测精灵元素之间是否碰撞。

碰撞检测 - 图1

  1. ;(async function () {
  2. const birdsJsonUrl = 'https://s5.ssl.qhres.com/static/5f6911b7b91c88da.json';
  3. const birdsRes = 'https://p.ssl.qhimg.com/d/inn/c886d09f/birds.png';
  4. const scene = new Scene('#obbcollision', {viewport: ['auto', 'auto'], resolution: [1540, 600]});
  5. const layer = scene.layer('fglayer');
  6. await scene.preload([birdsRes, birdsJsonUrl]);
  7. const bird = new Sprite('bird1.png');
  8. bird.attr({
  9. anchor: [0.5, 0.5],
  10. pos: [50, 200],
  11. offsetPath: 'M0,100C0,100,200,-100,500,100S700,-100,1000,100S1200,-100,1700,100S2200,-100,2700,100',
  12. });
  13. layer.append(bird);
  14. bird.animate([
  15. {textures: 'bird1.png'},
  16. {textures: 'bird2.png'},
  17. {textures: 'bird3.png'},
  18. {textures: 'bird1.png'},
  19. ], {
  20. duration: 300,
  21. iterations: Infinity,
  22. direction: 'alternate',
  23. easing: 'step-end',
  24. });
  25. bird.animate([
  26. {offsetDistance: 0},
  27. {offsetDistance: 1},
  28. ], {
  29. duration: 6000,
  30. iterations: Infinity,
  31. });
  32. function createRandomBlock() {
  33. const block = new Sprite();
  34. const x = Math.round(1540 * Math.random());
  35. const y = Math.round(600 * Math.random());
  36. const rotate = 360 * Math.random();
  37. block.attr({
  38. pos: [x, y],
  39. rotate,
  40. bgcolor: '#37c',
  41. size: [30, 70],
  42. opacity: 0.5,
  43. });
  44. layer.append(block);
  45. return block;
  46. }
  47. const blocks = [];
  48. for(let i = 0; i < 500; i++) {
  49. blocks.push(createRandomBlock());
  50. }
  51. layer.on('update', (evt) => {
  52. blocks.forEach((block) => {
  53. if(bird.OBBCollision(block)) {
  54. block.attr('bgcolor', '#c73');
  55. } else {
  56. block.attr('bgcolor', '#37c');
  57. }
  58. });
  59. });
  60. }())