0
Buttons to move objects and characters in html5 canvas (game)
Community Beginner
,
/t5/animate-discussions/buttons-to-move-objects-and-characters-in-html5-canvas-game/td-p/11610023
Nov 19, 2020
Nov 19, 2020
Copy link to clipboard
Copied
I remember you could make games where something could move with buttons like wasd or any other button (in actionscript)
Can you do this in html5 canvas?
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting.
Learn more
Community Expert
,
LATEST
/t5/animate-discussions/buttons-to-move-objects-and-characters-in-html5-canvas-game/m-p/11610181#M337698
Nov 19, 2020
Nov 19, 2020
Copy link to clipboard
Copied
Hi.
Yeah. It's totally possible.
Sample (simple):
Sample (advanced):
Here are two approaches to move a character using keyboard keys:
Simple:
var root = this;
var player = root.player; // player is the instance name assigned in the Properties panel
root.main = function()
{
root.keyForce = 5;
window.addEventListener("keydown", root.keyDownHandler);
window.addEventListener("keyup", root.keyUpHandler);
};
root.keyDownHandler = function(e)
{
if (e.key === "a" || e.key === "ArrowLeft")
player.x -= root.keyForce;
else if (e.key === "d" || e.key === "ArrowRight")
player.x += root.keyForce;
if (e.key === "w" || e.key === "ArrowUp")
player.y -= root.keyForce;
else if (e.key === "s" || e.key === "ArrowDown")
player.y += root.keyForce;
};
root.main();
Advanced:
var root = this;
var player = root.player; // player is the instance name assigned in the Properties panel
var keys = {};
root.main = function()
{
root.friction = 0.95;
root.keyForce = 50;
player.vX = 0;
player.vY = 0;
player.minVX = 20;
player.minVY = 20;
window.addEventListener("keydown", root.keyDownHandler);
window.addEventListener("keyup", root.keyUpHandler);
root.on("tick", root.tickHandler);
};
root.keyDownHandler = function(e)
{
keys[e.key] = true;
};
root.keyUpHandler = function(e)
{
delete keys[e.key];
};
root.tickHandler = function(e)
{
if (keys.a || keys.ArrowLeft)
player.vX -= root.keyForce;
else if (keys.d || keys.ArrowRight)
player.vX += root.keyForce;
if (keys.w || keys.ArrowUp)
player.vY -= root.keyForce;
else if (keys.s || keys.ArrowDown)
player.vY += root.keyForce;
player.vX *= root.friction;
player.vY *= root.friction;
player.x += player.vX * e.delta * 0.001;
player.y += player.vY * e.delta * 0.001;
if (Math.abs(player.vX) > 0 && Math.abs(player.vX) < player.minVX)
player.vX = 0;
if (Math.abs(player.vY) > 0 && Math.abs(player.vY) < player.minVY)
player.vY = 0;
};
root.main();
Files / source / code / FLA:
https://github.com/joao-cesar/adobe/tree/master/animate%20cc/html5_canvas/move_char_using_keys
I hope these help.
Regards,
JC
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting.
Learn more

