Reputation: 14141
I have a basic game moving a sprite around a map using Quintus html5 game. I have the sprite moving from square to square (64px) with a keypress fine. I want the player to move one square also when a button is click on the webpage.
I am unsure how to call the step
method in Quintus from a button click.
Outside the canvas I have a <button id="move-player">Move Player One Square</button>
document.getElementById("move-player").addEventListener("click", function( event ) {
//move player one square by possibly calling PlayerControls step
});
Quintus player code
Q.component("PlayerControls", {
// default properties to add onto our entity
defaults: {speed: 32, direction: 'null'},
// called when the component is added to
// an entity
added: function () {
var p = this.entity.p;
// adding default properties
Q._defaults(p, this.defaults);
// every time our entity steps, call its step method
this.entity.on("step", this, "step");
},
step: function (dt) {
// entity's properties
var p = this.entity.p;
var total_points = Q.state.get("points");
if (total_points >= 4) {
Q.state.set("points", 4);
Q.stageScene("GameOverMsg", 2);//display game over message
}//inner if
// direction from the input will help in animation
p.direction = Q.inputs['left'] ? 'left' :
Q.inputs['right'] ? 'right' :
Q.inputs['up'] ? 'up' :
Q.inputs['down'] ? 'down' : null;
window.onkeyup = function (e) {
if (e.keyCode == 37)//left
{
p.x -= p.speed;
move_collision = "left";
}
else if (e.keyCode == 38)//up
{
if (!(p.y <= 36)) {
p.y -= p.speed;
move_collision = "up";
}
}
else if (e.keyCode == 39)//right
{
p.x += p.speed;
move_collision = "right";
}
else if (e.keyCode == 40)//down
{
if (!(p.y >= 480)) {
p.y += p.speed;
move_collision = "down";
}
}
};
// movement
switch (move_collision) {
case "left":
p.x -= p.speed;
move_collision = "";
break;
case "right":
p.x += p.speed;
move_collision = "";
break;
case "up":
p.y -= p.speed;
move_collision = "";
break;
case "down":
if (!(p.y >= 480)) {
p.y += p.speed;
}
move_collision = "";
break;
default:
break;
}
}
});
//Player Sprite
Q.Sprite.extend("Player",
{
init: function (properties) {
properties.sheet = "snailspritesheet";
properties.sprite = "snail";
properties.frame = 4;
this._super(properties);
this.add("2d,PlayerControls,animation,tween");
Upvotes: 0
Views: 410
Reputation: 161
Consider that step
function is a kind of callback function.
That function is called periodically with timer.
So, there are two method to move a player
- Make a state machine: change state when button is clicked and interleave the code to
step
function for moving player- Make a trigger function to move a player with global variable: for example,
var player;
Q.scene("start",function(stage) {
stage.insert(new Q.UI.Button({
asset: 'move.png',
x: Q.width/2,
scale: 0.5,
y: 370
}, function() {
player.x += 10;
player.y -= 10;
})
);
}
I hope it is useful to you.
Upvotes: 1