9
« on: November 11, 2011, 09:43:54 pm »
Trying to play around with this stuff. This bit of code is supposed to create Triangles at the center of the screen, give them random velocity and spin, then display their movement.
#include <SFML/Graphics.hpp>
#include <iostream>
#include <math.h>
#include <time.h>
#include <vector>
sf::Vector2f origin;
sf::Vector2f gravity;
int frames;
float getrand(float a, float b)
{
return ((b-a)*((float)rand()/RAND_MAX))+a;
}
struct Triangle
{
sf::Shape Tri;
sf::Vector2f Pos;
sf::Vector2f Vel;
float Spin;
Triangle()
{
Tri.AddPoint(0,10);
Tri.AddPoint(20,0);
Tri.AddPoint(20,20);
Tri.SetOrigin(10,10);
Tri.SetPosition(origin);
Pos = Tri.GetPosition();
Spin = getrand(-360.f,360.f);
Vel.x = getrand(-.5f,.5f);
Vel.y = getrand(-.5f,.5f);
}
void Draw(sf::RenderWindow &app)
{
app.Draw(Tri);
}
void Physics()
{
Vel = sf::Vector2f(Vel.x + gravity.x/frames ,Vel.y + gravity.y/frames);
Pos = sf::Vector2f(Pos.x + Vel.x/frames ,Pos.y + Vel.y/frames);
Tri.SetPosition(Pos);
Tri.Rotate(Spin/frames);
}
};
int main()
{
srand((unsigned)time(0));
origin.x = 400;
origin.y = 300;
gravity.x = 0;
gravity.y = 3;
std::vector<Triangle*> triangles;
sf::RenderWindow App(sf::VideoMode(800,600,32),"oh man");
int frames = 60;
App.SetFramerateLimit(frames);
while (App.IsOpened())
{
sf::Event Event;
while (App.PollEvent(Event))
{
// Close window : exit
if (Event.Type == sf::Event::Closed)
App.Close();
// Escape key : exit
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Keyboard::Escape))
App.Close();
}
App.Clear();
Triangle* ptr = new Triangle;
triangles.push_back(ptr);
for (unsigned long x = 0; x < triangles.size(); x++)
{
std::cout<<triangles.at(0)->Pos.x<<" "<<triangles.at(0)->Pos.y<<"\n";
triangles.at(x)->Physics();
triangles.at(x)->Draw(App);
}
App.Display();
}
return EXIT_SUCCESS;
}
Two problems. The first is Triangle::Physics(); turns Vel and Pos into + Pos {x=-1.#IND000 y=1.#INF000 } sf::Vector2<float>
+ Vel {x=-1.#IND000 y=1.#INF000 } sf::Vector2<float>
Am I doing something wrong here?
Second, if I change Triangle::Physics to only increment Pos every time it's called, The call to Triangle::Draw(App); never ends up producing anything onscreen. If I only create one Triangle and never call Physics, it will display at the middle of the screen.