Sign in to follow this  
prchakal

How to make an sprite go to correct direction

Recommended Posts

Hi,

On my game i want that my shoot go to correct direction (enemy direction), but it doesnt occur.

You can see here:
[url]http://www.prsolucoes.com/downloads/solodefender.zip[/url]

The code that im using is (on update):



void Bullet::update()
{
updateSpriteDirection();
checkCollision();
updatePosition();
}

void Bullet::updateSpriteDirection()
{
sprite.SetRotation( Functions::angle(sprite.GetPosition().x, sprite.GetPosition().y, targetX, targetY) );
}

void Bullet::checkCollision()
{
if (sprite.GetPosition().x + sprite.GetSize().x < 0)
{
remove();
}
else if (sprite.GetPosition().y + sprite.GetSize().y < 0)
{
remove();
}
else if (sprite.GetPosition().x > Constants::SCREEN_WIDTH)
{
remove();
}
else if (sprite.GetPosition().y > Constants::SCREEN_HEIGHT)
{
remove();
}
}


void Bullet::updatePosition()
{
sprite.SetPosition(sprite.GetPosition().x + speedX, sprite.GetPosition().y + speedY);
}

void Bullet::updateSpeed()
{
if (sprite.GetPosition().x < targetX)
{
speedX = Constants::BULLET_SPEED;
}

if (sprite.GetPosition().x > targetX)
{
speedX = (Constants::BULLET_SPEED * -1);
}

if (sprite.GetPosition().y < targetY)
{
speedY = Constants::BULLET_SPEED;
}

if (sprite.GetPosition().y > targetY)
{
speedY = (Constants::BULLET_SPEED * -1);
}
}



What is wrong?

Im using SFML.

Share this post


Link to post
Share on other sites
I see you found an angle to point the texture in the (presumably) correct direction, but you never use that angle for the direction of the velocity. Since you want the bullet to move along that angle, you can use trigonometry to find how much you need to move on each axis, each frame. Lets say the amount the bullet needs to move each frame is (x, y), the speed of the bullet is s, and the angle is A, so using primary trig ratios cos(A) = x/s, therefore x = s * cos(A). Similarly, sin(A) = y/s, therefore y = s * sin(A). Using this you need to set the velocity, something like

// I am assuming sprite has a GetRotation method
speedX = Constants::BULLET_SPEED * cos(sprite.GetRotation());
speedY = Constants::BULLET_SPEED * sin(sprite.GetRotation());

Hope that helps.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this