sprite.js 969 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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) return
  19. ctx.drawImage(
  20. this.img,
  21. this.x,
  22. this.y,
  23. this.width,
  24. this.height
  25. )
  26. }
  27. /**
  28. * 简单的碰撞检测定义:
  29. * 另一个精灵的中心点处于本精灵所在的矩形内即可
  30. * @param{Sprite} sp: Sptite的实例
  31. */
  32. isCollideWith(sp) {
  33. const spX = sp.x + sp.width / 2
  34. const spY = sp.y + sp.height / 2
  35. if (!this.visible || !sp.visible) return false
  36. return !!(spX >= this.x
  37. && spX <= this.x + this.width
  38. && spY >= this.y
  39. && spY <= this.y + this.height)
  40. }
  41. }