Skip to content

Instantly share code, notes, and snippets.

@parasyte parasyte/menu.js
Last active Dec 29, 2015

Embed
What would you like to do?
Implementing a minimal, recursive menu system in melonJS.
game.MenuItem = me.GUI_Object.extend({
init : function (settings) {
this.pos = new me.Vector2d(settings.x, settings.y);
this.image = me.loader.getImage(settings.image);
this.parentMenu = settings.parentMenu;
this.subMenu = settings.subMenu;
this.callback = settings.callback;
this.name = "MenuItem";
},
onClick : function (e) {
// Only do stuff when our container is in the world.
if (!this.parentMenu.ancestor) {
return;
}
if (this.subMenu) {
// Remove my parent menu
if (this.parentMenu) {
me.game.world.removeChild(this.parentMenu);
}
// Add the new submenu
this.subMenu.parentMenu = this.parentMenu;
me.game.world.addChild(this.submenu);
}
if (this.callback) {
this.callback(this);
}
},
draw : function (context) {
context.drawImage(this.image, this.pos.x, this.pos.y);
}
});
game.Menu = me.ObjectContainer.extend({
init : function () {
this.parentMenu = null;
this.name = "Menu";
},
addMenuItem : function (settings) {
settings.parentMenu = this;
this.addChild(new game.MenuItem(settings));
},
goBack : function () {
if (this.parentMenu) {
me.game.world.removeChild(this);
me.game.world.addChild(this.parentMenu);
}
}
});
game.MenuScreen = me.ScreenObject.extend({
onResetEvent : function () {
// Create menus
this.rootMenu = new game.Menu();
var signedInMenu = new game.Menu();
var signUpMenu = new game.Menu();
var achievementsMenu = new game.Menu();
// Add menu items to root menu
this.rootMenu.addMenuItem({
x : 20,
y : 20,
image : "signInButton",
subMenu : signedInMenu
});
this.rootMenu.addMenuItem({
x : 20,
y : 100,
image : "signUpButton",
subMenu : signUpMenu
});
// Add menu items to signedInMenu
signedInMenu.addMenuItem({
x : 20,
y : 20,
image : "playButton",
callback : function () {
me.state.change(me.state.PLAY);
}
});
signedInMenu.addMenuItem({
x : 20,
y : 100,
image : "achievementsButton",
subMenu : achievementsMenu
});
signedInMenu.addMenuItem({
x : 20,
y : 180,
image : "goBackButton",
callback : signedInMenu.goBack
});
// ... Add more menu items
// Add the root menu to the game entity manager
me.game.world.addChild(this.rootMenu);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.