sprite.js 990 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * 游戏基础的精灵类
  3. */
  4. export default class Sprite {
  5. constructor(imgSrc = '', width= 0, height = 0, x = 0, y = 0) {
  6. this.img = new Image()
  7. this.img.src = imgSrc
  8. this.width = width
  9. this.height = height
  10. this.x = x
  11. this.y = y
  12. this.visible = true
  13. }
  14. /**
  15. * 将精灵图绘制在canvas上
  16. */
  17. drawToCanvas(ctx) {
  18. if ( !this.visible )
  19. return
  20. ctx.drawImage(
  21. this.img,
  22. this.x,
  23. this.y,
  24. this.width,
  25. this.height
  26. )
  27. }
  28. /**
  29. * 简单的碰撞检测定义:
  30. * 另一个精灵的中心点处于本精灵所在的矩形内即可
  31. * @param{Sprite} sp: Sptite的实例
  32. */
  33. isCollideWith(sp) {
  34. let spX = sp.x + sp.width / 2
  35. let spY = sp.y + sp.height / 2
  36. if ( !this.visible || !sp.visible )
  37. return false
  38. return !!( spX >= this.x
  39. && spX <= this.x + this.width
  40. && spY >= this.y
  41. && spY <= this.y + this.height )
  42. }
  43. }