I am struggling to understand what is wrong with my code for collision detection in a grid based game. I am trying to detect collision (intersections) between a "tile" rectangle and the "player" rectangle.
The tile rectangle is drawn at and x,y coordinate but the corners (bottom-left and top-right) of the rectangle are (x-16, y-16)(x+48, y+48).
The player rectangle depends on the player position but its corners should be at (player_x-16, player_y-16)(player_x+16, player_y+16).
I have tried using the built-in "(r Rect) Intersects(r Rect)" function from the pixel module but collision is only detected between the tie rectangle and the current player position (not with the offset of 16 pixels).
The "tiles" 2D array holds my map so I can check the type of tile the player is on.
I have also tried writing my own rectangle collision detection "algorithm" for lack of a better word ending up with the same result.
My character moves 4 pixels in whichever direction after each key press, I chess if the player is out of bounds (colliding with or inside of a wall) and if he is, move the character back 4 pixels.
Here is the relevant part of the code using the built-in function (I now have this) :
func (player Player) IsOutOfBounds(tiles [][]*world.Tile) bool {
x, y, _, _ := NormalizeCoordinates(player.Pos.X, player.Pos.Y)
//So now no need to loop through every cell since I know which one the player is touching
if strings.Contains(tiles[x][y].Type, "wall") || tiles[x][y].Type == "pillar" {
return true
}
return false
}
// I use this function to find the closest multiple of 32 from the player position which is going to be the index of the tile the player is in
func NormalizeCoordinates(player_x, player_y float64) (int, int, int, int) {
x := int(player_x + 32/2)
x -= x % 32
y := int(player_y + 32/2)
y -= y % 32
x2 := x + 32
y2 := y + 32
return x, y, x2, y2
}
In short :
Expected behavior : detect collision between set boundaries (player_x/y -/+ 16 and tile rectangle boundaries)
Current behavior : detecting collision between player_x/y and tile rectangle boundaries
Here's what it looks like for now, red is where I want it to detect collision and green is where its actually detecting:
Edit: Added a picture to illustrate my problem better and updated my question
x
andy
? – Nicky Logantrue
when there is an overlap? – Hymns For Disco