Hello! I am new and just beginning to learn about steering behavior. I need such behavior for the game I am making. Can you please look into my code and try to see what I am missing or at least misunderstood in terms of steering behavior?
My problem is that my sprite doesn't steer. So here is my code:
void PathFinder::moveToDestination( float e )
{
if( !_isPathFound ) return;
float tilesize = static_cast< float >( tileset->getTilesize() );
float speed = e * movableObjects->getVelocity();// NOTE : This should be getSpeed()
const float MAX_FORCE = 2.5;
const float mass = 80.0f;
const float tolerance = 1.0f;
sf::Vector2f desired_velocity;
sf::Vector2f steer;
sf::Vector2f velocity;
spritePosition.x = movableObjects->getSpritePositionX();
spritePosition.y = movableObjects->getSpritePositionY();
current_velocity = normalize( targetPosition - spritePosition );
desired_velocity = normalize( targetPosition - current_velocity ) * speed;
steer = desired_velocity - current_velocity;
steer = truncate< float >( steer , MAX_FORCE );
steer /= mass;
velocity = truncate< float >( current_velocity + steer , speed );
float movex = spritePosition.x + velocity.x;
float movey = spritePosition.y + velocity.y;
cout << " current velocity : " << current_velocity.x << " x " << current_velocity.y << endl;
cout << " desired velocity : " << desired_velocity.x << " x " << desired_velocity.y << endl;
cout << " steer : " << steer.x << " x " << steer.y << endl;
cout << " velocity : " << velocity.x << " x " << velocity.y << endl;
cout << endl;
if( abs( targetPosition.x - spritePosition.x ) <= tolerance
&& abs( targetPosition.y - spritePosition.y ) <= tolerance )
{
_isPathFound = false;
}
movableObjects->setSpritePosition( movex , movey );
}
Here is my code for VectorMath file which contains a bunch of templated functions: Maybe I got something wrong in here
#ifndef VECTORMATH_HPP #define VECTORMATH_HPP #include<cmath> template< typename T > T length( const sf::Vector2< T > &v ) { return sqrt( ( v.x * v.x ) + ( v.y * v.y ) ); } template< typename T > sf::Vector2< T > normalize( const sf::Vector2< T > &v ) { return v / length( v ); } template< typename T > sf::Vector2< T > truncate( const sf::Vector2< T > &v , float nmax ) { float i = nmax / length( v ); i = ( i < 1.0f )? 1.0f : i; sf::Vector2< T > n = v; n *= i; return n; } #endif // VECTORMATH_HPP
Thank you very much for your help and your time!