In this example, we demonstrate how to use UI elements like buttons and text in Beast2D. We create a simple menu scene with a styled "PLAY GAME" button and instructions, which transitions to a game scene upon click.
The addButton()
and addText()
functions allow you to build interactive menus and HUDs. The button's position, color states, and label properties are all customizable. We also show how to attach a function to the button's action
property to handle interactions.
In the second scene, a yellow box can be moved with the W, A, S, D keys, and the E key takes you back to the menu. This example highlights how scenes and UI logic can work together seamlessly.
DOWNLOAD EXAMPLE
//### EXAMPLE: UI ELEMENTS ###
//create menu scene and add to canvas
var menuScene = scene("MenuScene", canvas);
var menuBackground = menuScene.addBg("#3aa");
//add UI button
var play_button = menuScene.addButton("PLAY GAME", center());
play_button.color = "#00f";
play_button.color2 = "#00a";
play_button.label.font = "Consolas";
play_button.label.size = 24;
var size = play_button.getSize();
play_button.position = addVec(play_button.position, vec(-size[0]/2, 0));
play_button.tcolor = "yellow";
play_button.tcolor2 = "white";
//add UI text
var text = menuScene.addText("Click the Button", center());
text.font = "Georgia";
text.size = 24;
var size2 = text.getSize();
text.position = addVec(text.position, vec(-size2.width/2 + 10, -50));
//create the game scene
var myScene = scene("MyScene", canvas);
var text2 = myScene.addText('Press "E" to go back!', center());
text2.font = "Georgia";
text2.size = 24;
var size3 = text.getSize();
text2.position = addVec(text2.position, vec(-size3.width/2 + 10, -100));
//add background and game object
var myBackground = myScene.addBg("black");
var box = myScene.addGameObject("box");
box.materials[0].renderer.fill = false;
box.materials[0].renderer.color = "yellow";
//button action to switch scenes
play_button.action = function() {
myScene.run();
}
//input logic for movement and return
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;
if (canvas.input("E").down()) {
menuScene.run();
}
}
//run the menu scene
menuScene.run();
// global update function
function update() {
clear("black");
canvas.update();
setTimeout(update, canvas.timeout);
}
update();
Live view