I'm making a simple HTML5 RPG in pure JavaScript likened after Nox, Diablo or Titan Quest, with the character centered on the screen and the map moving around it.
TL;DR: My character, when colliding with the map edge, can still move outside the map in some cases. How do I quell this inconsistency?
Explanation: I have simple rectangles for the map, character, and one enemy, and I'm using bounding-box collision detection for them. When the character pushes against the map's edge, it stops moving, but the enemy box moves opposite of my character's trajectory of motion. When the enemy hits the wall, it stops, but the collision detection for my centered character fails and I'm flung into the void.
Here is a screenshot demonstrating this (map=white, character=blue, enemy=red):
Here are some bits of relevant code that might help:
Box object:
function Box() {
this.x = 0;
this.y = 0;
this.width = 50;
this.height = 50;
this.init = function(x, y, w, h, c) {
...
};
this.move = function(dir, amt, reverse) {
...
};
// stops 'obj' from leaving 'this'
this.constrain = function(obj) {
if(this.x > obj.x) {
this.x = obj.x;}
if(this.y > obj.y) {
this.y = obj.y;}
if(this.x + this.width < obj.x + obj.width) {
this.x = obj.x + obj.width - this.width;}
if(this.y + this.height < obj.y + obj.height) {
this.y = obj.y + obj.height - this.height;}
};
this.draw = function() {...};
}
Main code:
var m = new Box();
var p = new Box();
var e = new Box();
function rand(a, b) {return ((Math.random()* (b - a)) + a);}
// monster moves away from player on player collision with map.
// player moves off map on monster collision with map.
function init() {
p.init(cn.width/2 - p.width/2, cn.height/2 - p.height/2, 20, 20, "blue");
m.init(p.x, p.y, 200, 200, "white");
e.init(rand(m.x, m.x + m.width - e.width), rand(m.y, m.y + m.height - e.height), 20, 20, "red");
}
function update() {
if(key.left) {
m.move('left', p.speed, true);
e.move('left', p.speed, true);
}
...
m.constrain(p);
m.constrain(e);
}
function draw() {
c.clearRect(0, 0, cn.width, cn.height);
m.draw();
p.draw();
e.draw();
}
How would I make both the monster and the character consistently collide with the map?
I'm sorry in advance if the code/post is too long. I spent a good, long while shortening it up. I'll happily edit it, just ask. Thank you! :)