13
« on: June 25, 2010, 08:10:00 am »
Here I coded a working collision demo for you:
#include <SFML/Graphics.hpp>
#include "collision.h"
#include <iostream>
#include <string>
int main()
{
sf::RenderWindow App(sf::VideoMode(1024,768),"Collision Demo");
App.SetFramerateLimit(60.f);
sf::Image IMGBackground,IMGPlayer,IMGobstacle;
IMGBackground.LoadFromFile("bg.jpg");
IMGPlayer.LoadFromFile("player.png");
IMGobstacle.LoadFromFile("obstacle.png");
sf::Sprite Player(IMGPlayer);
sf::Sprite Background(IMGBackground);
sf::Sprite Obstacle(IMGobstacle);
Player.SetCenter(Player.GetSize()*.5f);
Obstacle.SetCenter(Obstacle.GetSize()*.5f);
Background.Resize(2000,2000);
Background.Move(-500,-500);
Player.Move(512,384);
Obstacle.Move(100,100);
sf::Vector2f Center(1000,1000);
sf::Vector2f HalfSize(App.GetWidth()*.5f,App.GetHeight()*.5f);
sf::View View(Center,HalfSize);
sf::Event evt;
std::string lastKey="";
float timer;
while(App.IsOpened())
{
while(App.GetEvent(evt))
{
if(evt.Type==sf::Event::Closed){App.Close();}
if(evt.Type==sf::Event::KeyPressed&&evt.Key.Code==sf::Key::Escape){App.Close();}
}
timer=App.GetFrameTime();
if(App.GetInput().IsKeyDown(sf::Key::Down)){if(Collision::BoundingBoxTest(Player,Obstacle)==false){Player.Move(0,100*timer);lastKey="D";}else if(lastKey=="D"){Player.Move(0,-100*timer);}else{Player.Move(0,100*timer);}}
if(App.GetInput().IsKeyDown(sf::Key::Up)){if(Collision::BoundingBoxTest(Player,Obstacle)==false){Player.Move(0,-100*timer);lastKey="U";}else if(lastKey=="U"){Player.Move(0,100*timer);}else{Player.Move(0,-100*timer);}}
if(App.GetInput().IsKeyDown(sf::Key::Right)){if(Collision::BoundingBoxTest(Player,Obstacle)==false){Player.Move(100*timer,0);lastKey="R";}else if(lastKey=="R"){Player.Move(-100*timer,0);}else{Player.Move(100*timer,0);}}
if(App.GetInput().IsKeyDown(sf::Key::Left)){if(Collision::BoundingBoxTest(Player,Obstacle)==false){Player.Move(-100*timer,0);lastKey="L";}else if(lastKey=="L"){Player.Move(100*timer,0);}else{Player.Move(-100*timer,0);}}
View.SetCenter(Player.GetPosition());
App.Clear();
App.SetView(View);
App.Draw(Background);
App.Draw(Obstacle);
App.Draw(Player);
App.Display();
}
return 0;
}