Detección de colisiones en el borde del lienzo.
Estoy haciendo un pequeño juego con mis amigos, pero estoy tratando de detectar la colisión al chocar contra las paredes del lienzo, y lo hice funcionar, pero cuando golpeo la pared mi personaje se atasca ... y no sé cómo hacerlo. Encuentra una manera de hacerlo mover de nuevo. ¿Crees que alguno de ustedes podría ayudarme con esto? Gracias por toda la ayuda!
Javascript / jQuery:
function Player() {
this.w = 50;
this.h = 60;
this.x = (cW / 2) - (this.w / 2);
this.y = (cH / 2) - (this.h / 2);
this.name = username.value;
this.nw = ctx.measureText(this.name).width; // username.clientWidth + 1;
this.src = playerImage;
this.dx = 0;
this.dy = 0;
this.render = function() {
ctx.drawImage(this.src, this.x, this.y, this.w, this.h);
ctx.fillStyle = 'orange';
ctx.font = '15px Arial, sans-serif';
// fixa x-värdet
ctx.fillText(this.name, (this.x + this.w / 2) - (this.nw / 2), (this.y - 6));
}
}
var player = new Player();
function animate() {
if(player.x > 0 && player.y > 0 && player.x + player.w < cW && player.y + player.h < cH) {
player.x += spd * player.dx;
player.y += spd * player.dy;
}
else {
// Need code here to release player from wall
}
ctx.save();
ctx.clearRect(0, 0, cW, cH);
ctx.drawImage(bg, 0, 0);
player.render();
ctx.rotate(-.4);
raining();
ctx.restore();
}
var animateInterval = setInterval(animate, 1000/60);
document.addEventListener('keydown', function(e) {
var key_press = String.fromCharCode(e.keyCode);
switch(key_press) {
case 'W':
player.dy = -1;
break;
case 'A':
player.dx = -1;
break;
case 'S':
player.dy = 1;
break;
case 'D':
player.dx = 1;
break;
default:
break;
}
});
document.addEventListener('keyup', function(e) {
var key_press = String.fromCharCode(e.keyCode);
switch(key_press) {
case 'W':
player.dy = 0;
break;
case 'A':
player.dx = 0;
break;
case 'S':
player.dy = 0;
break;
case 'D':
player.dx = 0;
break;
default:
break;
}
});