Quantcast
Channel: GameDev.net
Viewing all articles
Browse latest Browse all 17825

C++ and SDL2 Tile Collision

$
0
0
I'm having trouble figuring out how to accomplish tile collision with SDL2 and C++. I have a 2D map vector which contains either a 1 or a 0 for each index. std::vector<std::vector<int> > map; That map contains data for which tiles can be collided with and which tiles cannot. Below is an example of what it could look like. {{0, 1, 0, 1, 0}, {1, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 0, 0, 0, 1}} I also have a player class which contains some simple update, draw, move, etc. functions. All the player's logic takes place in the update function. The player's position information is stored in an SDL_RECT like so. SDL_RECT player_rectangle; player_rectangle.x = 0; player_rectangle.y = 0; player_rectangle.w = 16; player_rectangle.h = 16; As you may know by now, each tile in this game is 16 by 16 pixels. And movement in the game is tile-based. In the update function, I'm able to correct collisions with the edge of the map like so. void update() { // Process movement if (player_rectangle.x < 0) player_rectangle.x = 0; if (player_rectangle.x > map_rectangle.w - 16) player_rectangle.x = map_rectangle.w - 16; if (player_rectangle.y < 0) player_rectangle.y = 0; if (player_rectangle.y > map_rectangle.h - 16) player_rectangle.y = map_rectangle.h - 16; } My issue with understanding how to do this lies in the fact that the player's position is measured in pixels, while the map's tiles are measured as a grid, each index being 16 by 16 pixels. I've tried dividing the player's position by the tile's size in order to convert it to a grid so that I could try something similar to this. if (map[player_rectangle.y / 16][player_rectangle.x / 16] == 1) // Correct collision But this doesn't work all the time since the player's x and y positions aren't always factors of 16 when the player is moving between tiles. In fact, I can't even figure out how I would correct this collision even if I could figure out how to map out the player's position to the collision map. I'm aware this probably isn't the best approach, so I'm open to better ideas for accomplishing this.

Viewing all articles
Browse latest Browse all 17825

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>