Skip to content

Commit 7b18650

Browse files
committed
Section 22: Detecting a Win
1 parent e547116 commit 7b18650

2 files changed

Lines changed: 31 additions & 14 deletions

File tree

22-Javascript-with-the-Canvas-API/02-Maze copy/index.js

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Matter.js library
2-
const { Engine, Render, Runner, World, Bodies, Body } = Matter
2+
const { Engine, Render, Runner, World, Bodies, Body, Events } = Matter
33

4-
const cells = 15
4+
const cells = 3
55
const width = 600
66
const height = 600
77

@@ -173,28 +173,27 @@ const goal = Bodies.rectangle(
173173
unitLength * 0.7,
174174
unitLength * 0.7,
175175
{
176-
isStatic: true
176+
label: 'goal',
177+
isStatic: true,
177178
}
178179
)
179180
World.add(world, goal)
180181

181182
// Ball
182-
const ball = Bodies.circle(
183-
unitLength / 2,
184-
unitLength / 2,
185-
unitLength / 4
186-
)
183+
const ball = Bodies.circle(unitLength / 2, unitLength / 2, unitLength / 4, {
184+
label: 'ball',
185+
})
187186
World.add(world, ball)
188187

189-
document.addEventListener('keydown', event => {
188+
document.addEventListener('keydown', (event) => {
190189
// console.log(event.keyCode)
191190
// console.log(event);
192191

193-
const {x, y} = ball.velocity
194-
console.log(x, y);
192+
const { x, y } = ball.velocity
193+
console.log(x, y)
195194
if (event.keyCode === 38) {
196195
// console.log('move ball up')
197-
Body.setVelocity(ball, {x, y: y - 5})
196+
Body.setVelocity(ball, { x, y: y - 5 })
198197
}
199198
if (event.keyCode === 39) {
200199
// console.log('move ball right')
@@ -208,4 +207,20 @@ document.addEventListener('keydown', event => {
208207
// console.log('move ball left')
209208
Body.setVelocity(ball, { x: x - 5, y })
210209
}
211-
})
210+
})
211+
212+
// Win Condition
213+
Events.on(engine, 'collisionStart', (event) => {
214+
// console.log(event);
215+
event.pairs.forEach((collision) => {
216+
// console.log(collision)
217+
const labels = ['ball', 'goal']
218+
219+
if (
220+
labels.includes(collision.bodyA.label) &&
221+
labels.includes(collision.bodyB.label)
222+
) {
223+
console.log('User won!')
224+
}
225+
})
226+
})

22-Javascript-with-the-Canvas-API/README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,4 +87,6 @@ console.log(grid)
8787

8888
## 24. 28 Adding Keyboard Controls
8989

90-
## 25. 29 Disabling Gravity
90+
## 25. 29 Disabling Gravity
91+
92+
## 26. 30 Detecting a Win

0 commit comments

Comments
 (0)