Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function spawnGridCharacter(options = {}) {
- const char = options.char || "@";
- const color = options.color || "white";
- const layer = options.layer || 10;
- let x = options.x || cursor.x;
- let y = options.y || cursor.y;
- // Draw initial
- writeCharAt(char, layer, x, y, color);
- function move(dx, dy) {
- const oldX = x;
- const oldY = y;
- x += dx;
- y += dy;
- writeCharAt(" ", layer, oldX, oldY);
- writeCharAt(char, layer, x, y, color);
- }
- // KEYBOARD INPUT
- function onKeyDown(e) {
- if (e.repeat) return; // Prevent holding key from repeating
- if (e.key === "ArrowUp") move(0, -1);
- if (e.key === "ArrowDown") move(0, 1);
- if (e.key === "ArrowLeft") move(-1, 0);
- if (e.key === "ArrowRight") move(1, 0);
- }
- window.addEventListener("keydown", onKeyDown);
- // ---------------------------------------
- // ONSCREEN ARROW KEYS
- // ---------------------------------------
- function createButton(txt, dx, dy) {
- const btn = document.createElement("button");
- btn.textContent = txt;
- btn.style.fontSize = "24px";
- btn.style.margin = "4px";
- btn.style.width = "50px";
- btn.style.height = "50px";
- btn.addEventListener("mousedown", () => move(dx, dy));
- btn.addEventListener("touchstart", (e) => {
- e.preventDefault();
- move(dx, dy);
- });
- return btn;
- }
- // Container for onscreen buttons
- const pad = document.createElement("div");
- pad.style.position = "fixed";
- pad.style.bottom = "20px";
- pad.style.left = "20px";
- pad.style.display = "grid";
- pad.style.gridTemplateColumns = "50px 50px 50px";
- pad.style.gridTemplateRows = "50px 50px 50px";
- pad.style.gap = "4px";
- pad.style.userSelect = "none";
- pad.appendChild(document.createElement("div")); // empty
- pad.appendChild(createButton("↑", 0, -1)); // up
- pad.appendChild(document.createElement("div")); // empty
- pad.appendChild(createButton("←", -1, 0)); // left
- pad.appendChild(document.createElement("div")); // empty
- pad.appendChild(createButton("→", 1, 0)); // right
- pad.appendChild(document.createElement("div")); // empty
- pad.appendChild(createButton("↓", 0, 1)); // down
- pad.appendChild(document.createElement("div")); // empty
- document.body.appendChild(pad);
- return {
- stop() {
- window.removeEventListener("keydown", onKeyDown);
- pad.remove();
- },
- setChar(newChar) {
- writeCharAt(" ", layer, x, y);
- writeCharAt(newChar, layer, x, y, color);
- },
- setColor(newColor) {
- writeCharAt(char, layer, x, y, newColor);
- },
- get position() { return { x, y }; }
- };
- }
- // Example usage:
- const player = spawnGridCharacter({
- char: "@",
- color: "white"
- });
Advertisement
Add Comment
Please, Sign In to add comment