I have 2 boxes, 1 is the player and the other one is the wall. I would like the player to stop moving if there is a wall in the direction that the player is moving on.
a plunker link is provided at the bottom of this question to show what the 2 boxes do.
useing w a s d to move the box, I need to know how the player can detect the wall and stop moving when it comes in contact with the wall? this mean the player and the wall can not be in the same position, and the player would have to go around the wall instead of through the wall.
I need this today and i will be up all night so please don't hesitate to comment or answer the question, thank you.
function Player(row, col) {
this.isUpKey = false;
this.isRightKey = false;
this.isDownKey = false;
this.isLeftKey = false;
this.row = row;
this.col = col;
this.color = "#f00";
}
function drawWalls() {
var walls = new Array();
function Wall (row,col) {
this.row = row;
this.col = col;
this.color = "#000";
}
walls[walls.length] = new Wall(5,5);
for (var b = 0; b < walls.length; b++) {
ctxWall.fillStyle = walls[b].color;
ctxWall.fillRect(walls[b].row*25, walls[b].col*25, 25, 25);
}
}
var players = [];
var ctxPlayer;
var ctxWall;
var currentPlayer;
window.onload = function() {
ctxPlayer = document.getElementById('c').getContext('2d');
ctxWall = document.getElementById('walls').getContext('2d');
currentPlayer = players[players.length] = new Player(2, 2);
setInterval(render, 25);
drawWalls();
}
window.onkeypress = doKeyDown;
function render() {
ClearPlayer();
drawPlayer();
}
function drawPlayer() {
for (var p = 0; p < players.length; p++) {
ctxPlayer.fillStyle = players[p].color;
ctxPlayer.fillRect(players[p].row * 25, players[p].col * 25, 25, 25);
}
}
function doKeyDown(e) {
console.log(e);
if (e.keyCode == 97) {
currentPlayer.isUpKey = true;
--currentPlayer.row;
}
if (e.keyCode == 100) {
currentPlayer.isDownKey = true;
++currentPlayer.row;
}
if (e.keyCode == 119) {
currentPlayer.isLeftKey = true;
--currentPlayer.col;
}
if (e.keyCode == 115) {
currentPlayer.isRightKey = true;
++currentPlayer.col;
}
}
function ClearPlayer() {
ctxPlayer.clearRect(0, 0, 600, 400);
}
function checkIfPlayerMovingIntoWall() { if (currentPlayer.topY > Wall.bottomY) { console.log("stop moving up"); } }
I tried something like this, but does not seem to do anything – Dalomo 14 mins ago