I have finally made it to work! Here is my code...
#include<iostream>
using std::cout;
using std::endl;
#include<string>
using std::string;
#include<cmath>
#include<SFML/Graphics.hpp>
#include<SFML/System/Clock.hpp>
#include "VectorMath.hpp"
class Actor
{
public:
Actor( const string &fname , float x , float y )
:
desired( sf::Vector2f( 0 , 0 ) ),
steer( sf::Vector2f( 0 , 0 ) ),
velocity( sf::Vector2f( 0 , 0 ) ),
maxForce( 15 ),
maxVelocity( 3 ),
mass( 10.0f )
{
if( !texture.loadFromFile( fname ) )
return;
sprite.setTexture( texture );
sprite.setPosition( x , y );
sprite.setOrigin( 16 , 16 );
position = sprite.getPosition();
}
virtual ~Actor()
{
}
void update( float e )
{
sf::Vector2f target = sf::Vector2f( mousepos );
steer = seek( target );
steer = truncate( steer , maxForce );
steer *= ( 1 / mass );
velocity = velocity + steer;
velocity = truncate( velocity , maxVelocity );
position = position + velocity;
cout << position.x << " x " << position.y << endl;
sprite.setPosition( position );
}
sf::Vector2f & seek( const sf::Vector2f &targetpos )
{
sf::Vector2f force;
desired = targetpos - position;
desired = normalize( desired );
desired *= maxVelocity;
force = desired - velocity;
return force;
}
void mouseListen( const sf::Vector2i &mpos )
{
mousepos = mpos;
}
void setPosition( const sf::Vector2f &position )
{
sprite.setPosition( position );
}
sf::Sprite & getSprite()
{
return sprite;
}
private:
sf::Vector2i mousepos;
sf::Texture texture;
sf::Sprite sprite;
sf::Vector2f position;
sf::Vector2f desired;
sf::Vector2f steer;
sf::Vector2f velocity;
const float maxForce;
const float maxVelocity;
float mass;
};
int main()
{
sf::RenderWindow window( sf::VideoMode( 800 , 600 , 32 ) , "Steering Behavior" );
window.setFramerateLimit( 30 );
Actor actor1( "crusader.png" , 400.0f , 300.0f );
sf::Clock clock;
while( window.isOpen() )
{
sf::Event event;
float elapsed = clock.restart().asSeconds();
while( window.pollEvent( event ) )
{
if( event.type == sf::Event::Closed )
{
window.close();
}
else if( event.type == sf::Event::KeyPressed )
{
if( event.key.code == sf::Keyboard::Key::Escape )
window.close();
}
}
sf::Vector2i mpos = sf::Mouse::getPosition( window );
actor1.mouseListen( mpos );
actor1.update( elapsed );
window.clear();
window.draw( actor1.getSprite() );
window.display();
}
return 0;
}
I got a problem, you see, I have a game and each entity in the game has attribute most importantly velocity. This is because I wanted to give an entity different speeds. Given the code I have given, how can I control speed? As time goes by that entity can change it speed.
Do I need additional computation on maxForce and mass?