Итак, вот мой код, над которым я работаю с использованием HTML5, CSS и Javascript:
function startGame() {
myGameArea.start();
//(width,height, "color", X,Y)
//my character
myGamePiece = new component(50, 50, "white", 0, 0);
//obstacle
myLines = new component(30, 89, "#1ab2ff", 1400, 70);
myLines2 = new component(89, 30, "red", 0, 800);
}
//game platform
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 1400;
this.canvas.height = 789;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 1);
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function(e) {
myGameArea.key = false;
})
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop: function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.gamearea = myGameArea;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
this.crashWith = function(otherobj) {
var myLeft = this.x;
var myRight = this.x + (this.width);
var myTop = this.y;
var myBottom = this.y + (this.height);
var otherLeft = otherobj.x;
var otherRight = otherobj.x + (otherobj.width);
var otherTop = otherobj.y;
var otherBottom = otherobj.y + (otherobj.height);
var crash = true;
if ((myBottom < otherTop) || (myTop > otherBottom) || (myRight < otherLeft) ||
(myLeft > otherRight)) {
crash = false;
}
return crash;
}
}
//speed, controls, crashing
function updateGameArea() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {
myGamePiece.speedX = -1;
}
if (myGameArea.key && myGameArea.key == 39) {
myGamePiece.speedX = 1;
}
if (myGameArea.key && myGameArea.key == 38) {
myGamePiece.speedY = -1;
}
if (myGameArea.key && myGameArea.key == 40) {
myGamePiece.speedY = 1;
}
if (myGamePiece.crashWith(myLines)) {
myGameArea.stop();
}
if (myGamePiece.crashWith(myLines2)) {
myGameArea.stop();
} else {
myGameArea.clear();
myGamePiece.newPos();
myGamePiece.update();
// myLines.x (obstacles at x-axis) - (negative) or + (positive) of the x-axis = *value* (value=speed of the movement of the obstacle)
myLines.x -= 1;
myLines.update();
myLines2.y -= 1;
myLines2.update();
}
}
пожалуйста, мне здесь очень нужна помощь. :(
Я все еще новичок в javascript и хочу плохо учиться, пожалуйста, помогите мне.