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