Help with C++/SFML

Mar 25, 2015 at 10:43pm
I am currently working on adding collision between a Sprite controlled by the player, and the walls of my tile map. At the moment the player can walk on any tile (or no tile at all), so I've been trying to figure out how to differentiate between tiles to no avail. Any help is appreciated, thanks.

#include <SFML/Graphics.hpp>
#include <iostream>
#include <fstream>
#include <Windows.h>

#define HEIGHT 25
#define WIDTH 80

int main()
{

std::ifstream openfile("Map1.txt");

sf::Texture tileTexture;
sf::Sprite tiles;

char map[HEIGHT][WIDTH];
int x, y, colMap[HEIGHT][WIDTH];

sf::Texture Image;
Image.loadFromFile("player.png");
sf::Sprite Sprite(Image);
Sprite.setTextureRect(sf::IntRect(0, 0, 16, 16));

if (openfile.is_open() && !openfile.eof())
{
tileTexture.loadFromFile("tiles.png");
tiles.setTexture(tileTexture);

for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
{
openfile.get(map[i][j]);

if (map[i][j] == 'U')
{
Sprite.setPosition(j * 16, i * 16);
}
}
}
}

sf::RenderWindow Window(sf::VideoMode(480, 360, 16), "Loading Map");
sf::View Sprite_view(sf::FloatRect(0, 0, Window.getSize().x, Window.getSize().y));

while (Window.isOpen())
{
sf::Event Event;
while (Window.pollEvent(Event))
{
switch (Event.type)
{
case sf::Event::Closed:
Window.close();
break;
}
}

Window.clear(sf::Color(0, 0, 0));

for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
{
switch (map[i][j])
{
case 'A':
x = 6;
y = 1;
colMap[i][j] = 1;
break;
case 'F':
x = 5;
y = 1;
colMap[i][j] = 0;
break;
case 'W':
x = 0;
y = 0;
colMap[i][j] = 1;
break;
case 'D':
x = 1;
y = 0;
colMap[i][j] = 0;
break;
case 'U':
x = 8;
y = 29;
colMap[i][j] = 0;
break;
case 'S':
x = 8;
y = 0;
colMap[i][j] = 0;
break;
default:
x = 6;
y = 1;
colMap[i][j] = 1;
};

tiles.setPosition(j * 16, i * 16);
tiles.setTextureRect(sf::IntRect(x * 16, y * 16, 16, 16));
Window.draw(tiles);
}
}

if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
Sprite.setTextureRect(sf::IntRect(16, 48, 16, 16));
Sprite.move(0, -0.05f);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
Sprite.setTextureRect(sf::IntRect(16, 32, 16, 16));
Sprite.move(+0.05f, 0);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
Sprite.setTextureRect(sf::IntRect(16, 16, 16, 16));
Sprite.move(-0.05f, 0);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
Sprite.setTextureRect(sf::IntRect(16, 0, 16, 16));
Sprite.move(0, +0.05f);
}

Sprite_view.setCenter(Sprite.getPosition());

Window.setView(Sprite_view);
Window.draw(Sprite);
Window.display();
}
}
Last edited on Mar 25, 2015 at 10:50pm
Mar 25, 2015 at 11:43pm
One technique is to check if the sprites of the various entities intersect using their dimensions. If any intersection is detected, a collision is triggered.

Edit: please use code tags

Aceix.
Last edited on Mar 25, 2015 at 11:44pm
Topic archived. No new replies allowed.