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
|
#include<SFML\Graphics.hpp>
#include<iostream> //sending things to the console to help find errors
using namespace sf;
bool doCirclesIntersect(const Vector2f& center1, float radius1,
const Vector2f& center2, float radius2);
int main(){
RenderWindow mainWindow(VideoMode(1080, 900), "Testing");
CircleShape circle(20);
circle.setFillColor(Color::Blue);
circle.setOutlineColor(Color::Red);
circle.setOutlineThickness(3);
circle.setPosition(540, 450);
CircleShape enemy(10);
enemy.setFillColor(Color::Red);
enemy.setOutlineColor(Color::Blue);
enemy.setOutlineThickness(3);
enemy.setPosition(300, 200);
while(mainWindow.isOpen()){
mainWindow.clear();
mainWindow.draw(enemy);
mainWindow.draw(circle);
mainWindow.display();
Event event;
while(mainWindow.pollEvent(event)){
if(event.type == Event::Closed)
mainWindow.close();
if(event.type == Event::KeyPressed){
if(Keyboard::isKeyPressed(Keyboard::Up)){
circle.move(0, -2); //move circle
if(doCirclesIntersect(circle.getPosition(), circle.getRadius(),
enemy.getPosition(), enemy.getRadius())){ //check if circle and
//enemy overlap
circle.move(0, 2); //if so, move circle back to where it was
}
}
else if(Keyboard::isKeyPressed(Keyboard::Down)){
circle.move(0, 2);
if(doCirclesIntersect(circle.getPosition(), circle.getRadius(),
enemy.getPosition(), enemy.getRadius())){
circle.move(0, -2);
}
}
else if(Keyboard::isKeyPressed(Keyboard::Left)){
circle.move(-2, 0);
if(doCirclesIntersect(circle.getPosition(), circle.getRadius(),
enemy.getPosition(), enemy.getRadius())){
circle.move(2, 0);
}
}
else if(Keyboard::isKeyPressed(Keyboard::Right)){
circle.move(2, 0);
if(doCirclesIntersect(circle.getPosition(), circle.getRadius(),
enemy.getPosition(), enemy.getRadius())){
circle.move(-2, 0);
}
}
}
}
enemy.move(.05, 0);
if(doCirclesIntersect(circle.getPosition(), circle.getRadius(),
enemy.getPosition(), enemy.getRadius()))
enemy.move(-.05, 0); //testing collisions while enemy is moving
}
return 0;
}
bool doCirclesIntersect(const Vector2f& center1, float radius1,
const Vector2f& center2, float radius2){
Vector2f dist = center1 - center2;
float r = radius1 + radius2;
return (dist.x*dist.x + dist.y*dist.y) < (r*r); //returns true if the circles intersect
}
|