1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
|
#include <SFML/Graphics.hpp>
#include <iostream>
#include <algorithm>
#include <vector>
class Player
{
public:
sf::Sprite player;
sf::RectangleShape rect;
float bottom, left, right, top;
std::vector<std::vector<bool> > mask;
Player(sf::Vector2f position, sf::Texture &texture)
{
sf::Image image;
image = texture.copyToImage();
for(int i = 0; i < image.getSize().x; i++)
{
std::vector<bool> tempMask;
for (int j = 0; j < image.getSize().y; j++)
{
if (image.getPixel(i, j).a > 0)
tempMask.push_back(true);
else
tempMask.push_back(false);
}
mask.push_back(tempMask);
}
player.setTexture(texture);
player.setPosition(position);
}
void update()
{
bottom = rect.getPosition().y + rect.getSize().y;
left = rect.getPosition().x;
right = rect.getPosition().x + rect.getSize().x;
top = rect.getPosition().y;
}
bool Collision(Player p)
{
if (right <= p.left || left >= p.right || top >= p.bottom || bottom <= p.top)
{
}
else
{
float colBottom, colTop, colLeft, colRight;
colBottom = std::min(bottom, p.bottom);
colTop = std::max(top, p.top);
colLeft = std::max(left, p.left);
colRight = std::min(right, p.right);
for (int i = colTop; i < colBottom; i++)
{
for(int j = colLeft; j < colRight; j++)
{
if(mask[j - left][i - top] && p.mask[j - p.left][i - p.top])
return true;
}
}
}
return false;
}
};
int main()
{
sf::RenderWindow window(sf::VideoMode (800,600), "Pixel Perfect Collision");
sf::Texture Tplayer;
Tplayer.loadFromFile("Warrior.png");
Player p1(Player(sf::Vector2f(10, 10), Tplayer)),
p2(Player(sf::Vector2f(100, 100), Tplayer));
while(window.isOpen())
{
sf::Event Event;
while(window.pollEvent(Event))
{
switch (Event.type)
{
case sf::Event::Closed:
window.close();
break;
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
p1.player.move(0.1f, 0);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
p1.player.move(-0.1f, 0);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
p1.player.move(0, -0.1f);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
p1.player.move(0, 0.1f);
}
p1.update();
p2.update();
if (p1.Collision(p2))
std::cout << "Collision!" << std::endl;
window.clear(sf::Color(0, 240, 255));
window.draw(p1.player);
window.draw(p2.player);
window.display();
}
}
|