Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: How to fire enemy bullet towards player  (Read 1920 times)

0 Members and 1 Guest are viewing this topic.

ESuth

  • Newbie
  • *
  • Posts: 3
    • View Profile
How to fire enemy bullet towards player
« on: April 22, 2020, 01:58:01 am »
So I have a component set up that will fire bullets forward from an enemy in a 2d scrolling shooter.

What I need to have is the bullets firing towards the player position in a line.

I have tried looking up various posts about this but everything I try doesn't work for some reason.

Can anyone help point out what I'm doing wrong. I have the initial position of the bullet when fired. And the player position. I'm finding the difference by subtracting bullet position from player position. But I am unsure how to use this in setPosition()?

Here is what I have:

void BulletPhysicsComponent::update(double dt)
{
   
    Vector2f bPos = _parent->getPosition();
    auto pl = _parent->scene->ents.find("player");
    Vector2f pPos = pl[0]->getPosition();
    Vector2f diff = pPos - bPos;


        _parent->setPosition(diff * (float)dt);
        _parent->setRotation((180 / b2_pi) * _body->GetAngle());
       
}

Fx8qkaoy

  • Newbie
  • *
  • Posts: 42
    • View Profile
Re: How to fire enemy bullet towards player
« Reply #1 on: April 23, 2020, 11:19:13 am »
Code: [Select]
_parent->setPosition(diff * (float)dt);

U have problems doing the interpolation. "setPosition" sets the absolute position which means that the bullet is independent of its initial or last pos, which is wrong. U have to take in account the position of the previous frames. I'm not really sure how u handle the whole algorithm, but from what u sent the following line shall solve the problem or at least be suggestive of what u have to do:

Code: [Select]
_parent->setPosition(bPos + diff * (float) dt);

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: How to fire enemy bullet towards player
« Reply #2 on: April 25, 2020, 01:15:34 am »
You can also just use "move" instead for relative movement.

It's important to note that the speed of your bullet will differ depending on its distance and will always take the same amount of time to reach the player (regardless of how far away it is).

Since you have a 2D vector of its direction, you only need to convert this to a unit vector. To do this, simply divide it by its length (to find its length, use the Pythagorean theorem).
Then you can multiply its unit vector (this is a 2D vector with a length of one) by how far you want it to move, allowing you to control its speed easily by multiplying it with delta time and also its speed.
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*