This example introduces keyboard input handling in Beast2D using the canvas.input()
system. A box is created on the canvas, and players can move it using the W, A, S, D keys. Each keypress updates the object's position in real-time.
The canvas.logic
function is used to continuously check for key states during runtime. This approach allows smooth, frame-based control of game objects and sets the stage for implementing responsive game mechanics like player movement or interaction systems.
This simple, powerful system is perfect for platformers, top-down games, and other interactive 2D gameplay styles where real-time player control is essential.
DOWNLOAD EXAMPLE
//### EXAMPLE: INPUT & EVENTS ###
//create first scene and add it to the default canvas
var myScene = scene("MyScene", canvas);
//now lets add a background to the scene
var myBackground = myScene.addBg("black");
//let add the box to the scene
var box = myScene.addGameObject("box");
box.materials[0].renderer.fill = false;
box.materials[0].renderer.color = "yellow";
//keyboard control logic
canvas.logic = function() {
if (canvas.input("D").down()) {
box.position.x += 1;
}
if (canvas.input("A").down()) {
box.position.x -= 1;
}
if (canvas.input("W").down()) {
box.position.y -= 1;
}
if (canvas.input("S").down()) {
box.position.y += 1;
}
}
//run the scene
myScene.run();
// global update function
function update() {
// Clear screen with black color
clear("black");
// Update the canvas object
canvas.update();
// Set the update to repeat
setTimeout(update, canvas.timeout);
}
update();
Live view