Bored one day and wanted to see if I could make an html5 game.
Super noob but would appreciate if anyone could tell me why my code is flawed (which it undoubtedly is) so I could learn from it.
My goal was simply to make a character walk across the screen.
I downloaded a Megaman 8-bit sprite-sheet and used that.
http://www.sprites-inc.co.uk/files/Classic/Megaman/MM8/megaman8bit.pngHTML:
Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Game</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<canvas id="game" width='800' height='600' style="border:2px solid #000000;"></canvas>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
CSS:
Code
@charset "utf-8";
/* CSS Document */
canvas {
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
}
Javascript:
Code
// JavaScript Document
var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
// loads player
//load spritesheet into a variable
var player = new Image();
player.src = 'images/megaman8bit.png';
//define intital player position
var playerx = 1
var playery = 576
//load intial image of player
player.onload = function() {
context.drawImage(player, 103, 9, 20, 24, playerx, playery, 20, 24);
};
//define variables for movement
var playerright = 0
//check keypress
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '39') {
// right arrow
canvas.width = canvas.width;
right();
if(playerright == 0){
context.drawImage(player, 188, 9, 23, 24, playerx, playery, 23, 24);
right1();
}
else if(playerright == 1){
context.drawImage(player, 218, 9, 16, 24, playerx, playery, 16, 24);
right1();
}
else if(playerright == 2){
context.drawImage(player, 238, 9, 16, 24, playerx, playery, 16, 24);
rightreset();
}
}
}
//movement
//right
//define movement right in pixels
function right() {
playerx = playerx + 10;
}
function right1(){
playerright = playerright + 1;
}
function rightreset(){
playerright = 0;
}