Answer the question
In order to leave comments, you need to log in
How to make control on the phone using buttons inside the game on html5 + js?
I am writing games that can be played in a browser on a computer or on phones (tablets).
I did the keyboard control, how to make buttons in the game, when pressed, the character moved?
Mouse control will not work.
If anyone can help here is the game code:
html5
<html>
<head>
<script src="game.js"></script>
</head>
<body>
<canvas width="800" height="600" id="screen"></canvas>
</body>
</html>
;(function(){
var Game = function(canvasId){
var canvas = document.getElementById(canvasId);
var screen = canvas.getContext('2d');
var gameSize = {
x: canvas.width,
y: canvas.height
};
this.bodies = [new Player(this, gameSize)];
var self = this;
var tick = function(){
self.update();
self.draw(screen, gameSize);
requestAnimationFrame(tick);
}
tick();
}
Game.prototype = {
update: function(){
for(var i = 0; i < this.bodies.length; i++){
this.bodies[i].update();
}
},
draw: function(screen, gameSize){
clearCanvas(screen, gameSize);
for(var i = 0; i < this.bodies.length; i++){
drawRect(screen, this.bodies[i]);
}
}
}
var Player = function(game, gameSize){
this.game = game;
this.size = {width:16, height:16};
this.position = {x: gameSize.x/2-this.size.width/2, y: gameSize.y/2-this.size.height/2};
this.keyboarder = new Keyboarder();
}
Player.prototype = {
update:function(){
if(this.keyboarder.isDown(this.keyboarder.KEYS.LEFT)) {
this.position.x -=2;
}
}
}
var Keyboarder = function(){
var keyState = {};
window.onkeydown = function(e){
keyState[e.keyCode] = true;
}
window.onkeyup = function(e){
keyState[e.keyCode] = false;
}
this.isDown = function(keyCode){
return keyState[keyCode] === true;
}
this.KEYS = {LEFT: 37, RIGHT: 39, SPACE: 32};
}
var drawRect = function(screen, body){
screen.fillRect(body.position.x, body.position.y, body.size.width, body.size.height);
}
var clearCanvas = function(screen, gameSize){
screen.clearRect(0,0,gameSize.x, gameSize.y);
}
window.onload = function(){
new Game("screen");
}
})();
Answer the question
In order to leave comments, you need to log in
Determine the environment in which the game is running and if it is a mobile system, then draw control buttons and a joystick.
If the game will be launched in the phone's browser -> you need to start from the screen size + browser (Safari, Opera Mini, etc.).
And it's easier to add a button: hiding-showing the keys for control, and so that the control keys are always there.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question