Skip to content

Instantly share code, notes, and snippets.

@luizbills
Last active November 30, 2023 04:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luizbills/b41e55d3eaeb2f01dd4a22ab5f6153e1 to your computer and use it in GitHub Desktop.
Save luizbills/b41e55d3eaeb2f01dd4a22ab5f6153e1 to your computer and use it in GitHub Desktop.
Kaboom.js - attack RPG-style
kaboom();
// debug.inspect = true
loadBean();
const player = add([
sprite('bean'),
pos(center()),
area(),
{
movespeed: 200,
hasSword: false,
}
])
const sword = add([
pos(center().add(-80)),
area({
shape: Rect.fromPoints(vec2(0), vec2(36,80))
}),
{
draw() {
drawRect({
width: 16,
height: 80,
pos: vec2(10, 0),
color: BLUE,
})
drawRect({
width: 36,
height: 8,
pos: vec2(0, 50),
color: BLUE,
})
}
},
"sword"
])
player.onCollide('sword', (sword) => {
destroy(sword);
player.hasSword = true;
})
const dirs = {UP, DOWN, LEFT, RIGHT}
let lastDir = 'UP'
onKeyPress('space', () => {
if (!player.hasSword) return;
let offset = vec2();
let size = vec2(16,80)
if (lastDir === 'UP') {
offset = offset.add(22,-80)
} else if (lastDir === 'DOWN') {
offset = offset.add(22, 52)
} else if (lastDir === 'LEFT') {
size = size.scale(0).add(80,16)
offset = offset.add(-80, 20)
} else if (lastDir === 'RIGHT') {
size = size.scale(0).add(80,16)
offset = offset.add(60, 20)
}
add([
pos(),
area(),
rect(size.x, size.y),
color(BLUE),
lifespan(0.1),
follow(player, offset),
"sword_hitbox"
])
})
for (const d in dirs) {
console.log(d)
onKeyDown(d.toLowerCase(), () => {
player.move(dirs[d].scale(player.movespeed))
lastDir = d
})
}
const ui = add([
pos(0,0),
fixed(),
text("Pick the sword and press SPACE to attack"),
color(RED)
])
for(let i = 0; i < 15; i++) {
add([
rect(40, 40),
area(),
color(GREEN),
pos(rand(width()),rand(height())),
"enemy"
])
}
onCollide("enemy", "sword_hitbox", (enemy) => {
destroy(enemy)
})