So, I'm making a game kinda in the same basis as Chris Pokémon Like Game. So, the player moves with the illusion of the background moving and all. But, I'm implementing more than I saw in the videos. Right now, I'm trying to sense correctly the mouse and the right block that the mouse is colliding with. But, I'm struggling with some disparity in the X axis. With the Y, it appears to function like it should. But with the X, depending on where the map position is, the mouse appears several pixels away from the block that I'm currently colliding with. I'm going to put here the collision detection (which I took from the Tower Defense Game). Please, help me :(
class BattleFloor {
static width = 32
static height = 32
static class = 'battleFloor'
constructor({ position, map }) {
this.position = position
this.width = 32
this.height = 32
this.size = 32;
this.class = 'battleFloor';
this.map = map;
this.color = 'rgba(255, 255, 255, 0)'
}
draw () {
context.fillStyle = this.color
context.fillRect(this.position.x, this.position.y, this.width, this.height)
}
update(mouse) {
this.draw();
if (mouse.x > this.position.x && mouse.x < this.position.x + this.size &&
mouse.y > this.position.y && mouse.y < this.position.y + this.size) {
this.color = 'rgba(255, 0, 0, 1)'
} else {
this.color = 'rgba(255, 255, 255, 1)'
}
}
}
In the game, the blocks are in the correct position and size, but the mouse collision is not working like it should for the X axis. I wish I could send a video to help seeing what I'm saying.
Is there any margin between your canvas and your browser window? Any bit of spacing can throw off your mouse position, so you'd need to add that bit of offset to your equation when detecting for coordinates.
You can get an element's offset with getBoundingClientRect(): https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
Want to participate?
Create a free Chris Courses account to begin