я следовал этому руководству , чтобы создать рисунок l oop в javascript. затем я добавил свои изображения и столкновение ... но иногда моя игра, кажется, игнорирует столкновение, хотя это не должно происходить, моя цель - чтобы изображение перемещалось на 1 пиксель за раз, пока нажата клавиша, и останавливалось, когда оно сталкивалось черный пиксель.
вы заметите, что в коде я использую переменную playerSpeed = 1, чтобы помочь перемещать изображение, но я вполне уверен, что мне нужно каким-то образом использовать переменную прогресса, чтобы предотвратить эту ошибку рисования?
//FIGHT GAME JS
/*NOTES
*/
var canvas = document.getElementById("Fight_Game_Canvas"),
ctx = canvas.getContext("2d"),
maze = new Image();
maze.src = "lib/level_1.png";
var mazeData,
//mazeName = [],
playerSpeed = 1,
left_collision_offset = -5*4,
right_collision_offset = 5*4,
up_collision_offset = -canvas.width*5*4,
down_collision_offset= canvas.width*5*4;
function clear_canvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); }
/////GAME LOOP TUTORIAL STUFF//////
ctx.fillStyle = "blue";
var playerState = {
x: 105, //sets location of square
y:485,
width: 10,
height: 10,
pressedKeys: {
left: false,
right: false,
up: false,
down: false
}//end pressedKeys
}//end playerState
var level = 1,
levelFiles = ["level_1.png", "maze2.png", "maze3.png"],
levelXStart = [10,10,10],
levelYStart = [235,10,10];
var keyMap = {
68: 'right',
65: 'left',
87: 'up',
83: 'down'
}
function keydown(event) {
var key = keyMap[event.keyCode]
playerState.pressedKeys[key] = true;
}//end keydown
function keyup(event) {
var key = keyMap[event.keyCode]
playerState.pressedKeys[key] = false;
console.log('playerState.x and y ', playerState.x, ' ', playerState.y);
}//end keyup
window.addEventListener("keydown", keydown, false);
window.addEventListener("keyup", keyup, false);
function update(progress) {
if ((playerState.pressedKeys.left) && (!checkCollision(left_collision_offset))) {
//if ((playerState.pressedKeys.left) && !collision) {
//playerState.x -= Math.round(progress/20);
playerState.x -= playerSpeed;
}
if ((playerState.pressedKeys.right) && (!checkCollision(right_collision_offset))) {
//if ((playerState.pressedKeys.right)) {
//playerState.x += Math.round(progress/20);
playerState.x += playerSpeed;
}
if ((playerState.pressedKeys.up) && (!checkCollision(up_collision_offset))) {
//if ((playerState.pressedKeys.up)) {
//playerState.y -= Math.round(progress/20);
playerState.y -= playerSpeed;
}
if ((playerState.pressedKeys.down) && (!checkCollision(down_collision_offset))) {
//playerState.y += Math.round(progress/20);
playerState.y += playerSpeed;
}
// stop moving at boundaries of canvas
if (playerState.x >= canvas.width) {
playerState.x = canvas.width
} else if (playerState.x <= 0) {
playerState.x = 0;
}
if (playerState.y >= canvas.height) {
playerState.y = canvas.height
} else if (playerState.y <= 0) {
playerState.y = 0;
}
}//end update
function draw() {
// Draw the State of the world
ctx.clearRect(0, 0, canvas.width, canvas.height)
draw_maze();
ctx.fillRect(playerState.x - 5, playerState.y - 5, 10, 10); //a square that can be removed, but is nice to keep for testing
ctx.drawImage(wugg, playerState.x-25, playerState.y-30);
if ((playerState.x >= 125) && (level == 1)) {
console.log ('STORY TIME');
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "black";
ctx.textAlign = "center";
ctx.fillText("A young prince was about to be hoisted into",
canvas.width/2, 30);
ctx.fillText("his arranged marriage while being prepped for",
canvas.width/2, 70);
ctx.fillText("his future royal duties.",
canvas.width/2, 110);
// ctx.fillText("However, there was a problem, this prince like many others, totally rejected his royal fate.",
// canvas.width/2, 150);
}//end if
}
function loop(timestamp) {
var progress = timestamp - lastRender;
update(progress);
draw();
lastRender = timestamp;
window.requestAnimationFrame(loop);
}
var lastRender = 0;
//window.requestAnimationFrame(loop);
//////END GAME LOOP STUFF//////
function draw_maze() {
//draw maze
ctx.drawImage (maze, 0, 0);
}//end draw_maze
var wugg = new Image();
wugg.src = "lib/wugg4.png";
//wugg.src = "lib/wugg_transparent.png";
/*wugg.onload = function() {
draw_wugg;
}*/
function draw_wugg(x,y ) {
ctx.drawImage(wugg, x,y);
}
//function checkCollision(offset)
function checkCollision(offset, color) {
//for now try to just use center of square as the 'edge' for simplicity
// alpha = 255 for visible, 0 for transparent
var mazeDataArrayLocation;
mazeDataArrayLocation = ((canvas.width * playerState.y) + playerState.x) *4;
if (offset) {
mazeDataArrayLocation += offset;
}//end if
if ((mazeData.data[mazeDataArrayLocation] == 0) && (mazeData.data[mazeDataArrayLocation + 1] == 0) && (mazeData.data[mazeDataArrayLocation + 2] == 0))
{ //if black pixel then return true
return true;
} else if ((mazeData.data[mazeDataArrayLocation] == 0) && (mazeData.data[mazeDataArrayLocation + 1] == 0) && (mazeData.data[mazeDataArrayLocation + 2] == 255))
{ //if blue pixel then go next lelvel
console.log('LEVEL FINISHED!!!');
prep_next_level();
} else if ( playerState.x >= canvas.width)
{ //if at end of map, then go next level
prep_next_level();
} //end if
return false; //false if black pixel not found at center of square (for now)
}//end check collision
function prep_next_level(){
level++;
playerState.x = levelXStart[level-1];
playerState.y = levelYStart[level-1];
maze.src = "lib/" + levelFiles[level-1];
}
//***JQUERY LOADED***
$(document).ready(function() {
// all jQuery code goes here
//EVENTS
maze.onload = function() {
ctx.drawImage (maze, 0, 0);
console.log(' IMAGE LOADED');
mazeData = ctx.getImageData(0,0, canvas.width, canvas.height);
console.log ('MAZE DATA ', mazeData);
if (level ==1){
window.requestAnimationFrame(loop);
}//end if
}//end maze.onload
}); //end document ready