Skip to content
This repository has been archived by the owner on Nov 12, 2024. It is now read-only.

feat: adding camera rpg example #582

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions demo/cameraRPG.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Custom RPG-like camera entity
// Start a kaboom game with inpect on
kaboom().debug.inspect = true;

// Load assets
loadSprite("coin", "/sprites/coin.png");
loadSprite("grass", "/sprites/grass.png");

// Setup a basic level
const level = addLevel([" = $", "======="], {
width: 64,
height: 64,
pos: vec2(340, 600),
"=": () => [sprite("grass"), area(), solid(), origin("bot")],
$: () => [sprite("coin"), area(), origin("bot"), "coin"],
});

// Creating our camera entity
const camera = add([
pos(window.innerWidth / 2, window.innerHeight / 2),
layer("bg"),
area({ width: 30, height: 30 }),
origin("center"),
"camera",
{ mouseDownX: 0, mouseDownY: 0 },
]);

// Save starting click point
onMousePress((pos) => {
camera.mouseDownX = pos.x;
camera.mouseDownY = pos.y;
});

// Move kaboom camera calculating offsets
onMouseMove((pos) => {
// Calculate offsets only if mouse left is pressed
if (isMouseDown("left")) {
const movementX = pos.x - camera.mouseDownX;
const movementY = pos.y - camera.mouseDownY;
const offsetX = camera.pos.x - movementX;
const offsetY = camera.pos.y - movementY;
camPos(offsetX, offsetY);
}
});

// Move camera entity with offsets after mouse release
onMouseRelease(() => {
const pos = mousePos();
const movementX = pos.x - camera.mouseDownX;
const movementY = pos.y - camera.mouseDownY;
const offsetX = camera.pos.x - movementX;
const offsetY = camera.pos.y - movementY;
camera.moveTo(vec2(offsetX, offsetY));
});