Игра, над которой я работаю для класса, работает и готова сдаться, но что-то об этом беспокоило меня
Эй, я должен сделать последнее задание для своего вводного класса HTML javascript. Я делаю это из книги Роба Хоукса "Основа HTML 5 Canvas для игр и развлечений", стр.245 - 272. На данный момент игра работает и готов сдать, но что-то в этом меня беспокоило. Он настроен так, что когда вы не перемещаете свой плеер, он автоматически перетаскивает вас влево, но он продолжает исчезать с экрана. Я установил границы на верхней и правой стенах холста, но как мне сделать это с левой и нижней стенами холста? Я думаю, что это как-то связано с этой строкой в моем game.js ниже.
if(player.x-player.halfWidth < 20) {
player.x = 20+player.halfWidth;
} else if (player.x+player.halfWidth > canvasWidth-20) {
player.x = canvasWidth-20-player.halfWidth;
};
if(player.y-player.halfHeight < 20) {
player.y = 20+player.halfHeight;
} else if (player.y+player.halfHeight > canvasWidth-20) {
player.y = canvasHeight-20-player.halfHeight;
};
вот полная игра JS ниже
$(document).ready(function(){
var canvas = $("#gameCanvas");
var context = canvas.get(0).getContext("2d");
//canvas dimensions
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
//game settings
var playGame;
var asteroids;
var numAsteroids;
var player;
var score;
var scoreTimeout;
var arrowUp = 38;
var arrowRight = 39;
var arrowDown = 40;
//Game UI
var ui = $("#gameUI");
var uiIntro = $("#gameIntro");
var uiStats = $("#gameStats");
var uiComplete = $("#gameComplete");
var uiPlay = $("#gamePlay");
var uiReset = $(".gameReset");
var uiScore = $(".gameScore");
var soundBackground = $("#gameSoundBackground").get(0);
var soundThrust = $("#gameSoundThrust").get(0);
var soundDeath = $("#gameSoundDeath").get(0);
//reset and start game
var Asteroid = function (x, y, radius, vX){
this.x = x;
this.y = y;
this.radius = radius;
this.vX = vX;
};
var Player = function (x, y) {
this.x = x;
this.y = y;
this.width = 24;
this.height = 24;
this.halfWidth = this.width/2;
this.halfHeight = this.height/2;
this.vX = 0;
this. vY= 0;
this.moveRight = false;
this.moveUp = false;
this.moveDown = false;
this.flame = 20;
};
/*
}); */ //possibly breaks code
function startGame() {
//Reset game stats
uiScore.html("0");
uiStats.show();
//set up initial game settings
playGame = false;
asteroids= new Array();
numAsteroids = 20;
score = 0;
player = new Player(150, canvasHeight/2);
for (var i = 0; i < numAsteroids; i++) {
var radius = 5+(Math.random()*10);
var x = canvasWidth+radius+Math.floor(Math.random()*canvasWidth);
var y = Math.floor(Math.random()*canvasHeight);
var vX = -5-(Math.random()*5);
asteroids.push(new Asteroid(x, y, radius, vX));
};
//Start the animation loop
$(window).keydown(function(e) {
var keyCode = e.keyCode;
if(!playGame){
playGame = true;
soundBackground.currentTime = 0;
soundBackground.play();
animate();
timer();
};
if (keyCode == arrowRight){
player.moveRight = true;
if (soundThrust.paused) {
soundThrust.currentTime = 0;
soundThrust.play();
}
} else if (keyCode == arrowUp) {
player.moveUp = true;
} else if (keyCode == arrowDown) {
player.moveDown = true;
};
});
$(window).keyup(function(e) {
var keyCode = e.keyCode;
if (keyCode == arrowRight){
player.moveRight = false;
soundThrust.pause();
} else if (keyCode == arrowUp) {
player.moveUp = false;
} else if (keyCode == arrowDown) {
player.moveDown = false;
};
});
animate();
};
//Initialize the game environment
function init(){
uiStats.hide();
uiComplete.hide();
uiPlay.click(function(e) {
e.preventDefault();
uiIntro.hide();
startGame();
});
uiReset.click(function(e) {
e.preventDefault();
$(window).unbind("keyup");
$(window).unbind("keydown");
uiComplete.hide();
clearTimeout(scoreTimeout);
startGame();
});
};
function timer(){
if(playGame) {
scoreTimeout = setTimeout(function() {
uiScore.html(++score);
if (score % 5 == 0) {
numAsteroids += 5;
};
timer();
}, 1000);
};
};
//animation loop does that stuff that does all the fun stuff
function animate(){
//clear
context.clearRect(0, 0, canvasWidth, canvasHeight);
var asteroidsLength = asteroids.length;
for(var i = 0; i < asteroidsLength; i++) {
var tmpAsteroid = asteroids[i];
tmpAsteroid.x += tmpAsteroid.vX;
if(tmpAsteroid.x+tmpAsteroid.radius < 0) {
tmpAsteroid.radius = 5+(Math.random()*10);
tmpAsteroid.x = canvasWidth+tmpAsteroid.radius;
tmpAsteroid.y = Math.floor(Math.random()*canvasHeight);
tmpAsteroid.vX = -5-(Math.random()*5);
};
var dX = player.x - tmpAsteroid.x;
var dY = player.y - tmpAsteroid.y;
var distance = Math.sqrt((dX*dX)+(dY*dY));
if(distance < player.halfWidth+tmpAsteroid.radius) {
soundThrust.pause();
soundDeath.currentTime = 0;
soundDeath.play();
//game over
playGame=false;
clearTimeout(scoreTimeout);
uiStats.hide();
uiComplete.show();
soundBackground.pause();
$(window).unbind("keyup")
$(window).unbind("keydown")
};
context.fillStyle ="rgb(255, 255, 255)";
context.beginPath();
context.arc(tmpAsteroid.x, tmpAsteroid.y, tmpAsteroid.radius, 0, Math.PI*2, true);
context.closePath();
context.fill();
};
while (asteroids.length < numAsteroids) {
var radius = 5+(Math.random()*10);
var x = Math.floor(Math.random()*canvasWidth)+canvasWidth+radius;
var y = Math.floor(Math.random()*canvasHeight);
var vX = -5-(Math.random()*5);
asteroids.push(new Asteroid(x, y, radius, vX));
};
player.vX = 0;
player.vY = 0;
if (player.moveRight) {
player.vX = 3;
} else {
player.vX = -3;
};
if (player.moveUp) {
player.vY = -3;
};
if (player.moveDown) {
player.vY = 3;
};
if (player.moveRight) {
context.save();
context.translate(player.x-player.halfWidth, player.y);
if(player.x-player.halfWidth < 20) {
player.x = 20+player.halfWidth;
} else if (player.x+player.halfWidth > canvasWidth-20) {
player.x = canvasWidth-20-player.halfWidth;
};
if(player.y-player.halfHeight < 20) {
player.y = 20+player.halfHeight;
} else if (player.y+player.halfHeight > canvasWidth-20) {
player.y = canvasHeight-20-player.halfHeight;
};
if (player.flameLength == 20) {
player.flameLength = 15;
} else {
player.flameLength = 20;
};
context.fillStyle = "orange";
context.beginPath();
context.moveTo(0, -5);
context.lineTo(-player.flameLength, 0);
context.lineTo(0, 5);
context.closePath();
context.fill();
context.restore();
};
player.x += player.vX;
player.y += player.vY;
context.fillStyle = "rgb(255, 0, 0)";
context.beginPath();
context.moveTo(player.x+player.halfWidth, player.y);
context.lineTo(player.x-player.halfWidth, player.y-player.halfHeight);
context.lineTo(player.x-player.halfWidth, player.y+player.halfHeight);
context.closePath();
context.fill();
if(playGame){
//run the animation loop again in 33 milliseconds
setTimeout(animate,33);
};
};
init();
});
И ниже у меня есть HTML, я пишу JS для
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Asteroid Avoidance | James McGurn</title>
</head>
<body>
<audio id="gameSoundBackground" loop>
<source src="audio/background.ogg" type="audio/ogg">
<source src="audio/background.mp3" type="audio/mpeg">
</audio>
<audio id="gameSoundThrust" loop>
<source src="audio/thrust.ogg" type="audio/ogg">
<source src="audio/thrust.mp3" type="audio/mpeg">
</audio>
<audio id="gameSoundDeath">
<source src="audio/game_over.ogg">
<source src="audio/game_over.mp3">
</audio>
<div id="game">
<div id="gameUI">
<div id="gameIntro">
<h1>Asteroid Avoidance</h1>
<p>Click Play And Then Press Any Key To Start</p>
<p><a id="gamePlay" class="button" href="">Play</a></p>
</div><!--/#gameIntro -->
<div id="gameStats">
<p>Time: <span class="gameScore"></span> seconds</p>
<p><a class="gameReset" href="">Reset</a></p>
</div><!--/#gameStats -->
<div id="gameComplete">
<h1>Game over!</h1>
<p>You survived for <span class="gameScore"></span> seconds</p>
<p><a class="gameReset button" href="">Play Again</a></p>
</div><!--/#gameComplete -->
</div><!--/#gameUI -->
<canvas id="gameCanvas" width="800" height="600">
<!-- fallback content for non HTML 5 browsers -->
</canvas>
</div><!--/game -->
</body>
</html>
Я новичок в переполнении стека, так что, надеюсь, кто-нибудь сможет мне помочь и объяснить, как работает код, потому что я действительно разбираюсь в этом и хочу многому научиться