SFML - move an object towards a coordinate

so I am working on an AI system with C ++ and SFML in which I want the enemies to follow the player. I'm going to create it so that the enemies move to the point where the player was 30 frames ago (so it will constantly update). But my question is simple, what is the math that makes the enemy go to a certain point? For example, if the player is at (230, 400) and the enemy is at (100, 200), how do I get the enemy (using the .move () function at a speed of 3) to get to that point? Any help would be fantastic!

--- UPDATED BELOW WITH CURRENT CODE FOR MOTION HANDLING -----

float angle = atan2(v2iEnemyPos[1].y - rsPlayer.getPosition().y, v2iEnemyPos[1].x - rsPlayer.getPosition().x);
    angle =angle * 180 / (atan(1) * 4);
   sf::Vector2f newpos((cos(angle))*2, (sin(angle))*2);
    std::cout << newpos.x << " " << newpos.y << std::endl;
    rsEnemy[1].move(newpos.x, newpos.y);
    rwWinOne.draw(rsPlayer);
    rwWinOne.display();
    rwWinOne.clear();

      

+3


source to share


2 answers


The direction of movement of your enemy is simply the difference between the player's position and the enemy's position. However, you want the enemies to move at a constant speed, so you need to normalize the result. This will give you the direction as a vector of length 1.

Vector2u direction = normalize(player.getPosition() - enemy.getPosition());

      

Now you can multiply this direction by the speed constant of that enemy type. The result is a vector with a length that depends on the speed factor, not the distance to the player. Just use the result to move your enemy.

enemy.move(speed * direction);

      



However, you do this as soon as the frame and frames can differ between machines and configurations. So you have to add the elapsed time since the last call forwarding, which can be your frame time, as a factor in the equation. Thus, if the frame takes longer than usual, the enemy will be moved further to figure it out, and vice versa.

// Initialize a timer
sf::Clock clock;

// Get elapsed time at the beginning of a frame
// I multiply this by target framerate to get a value around one
float delta = clock.restart().asSeconds() * 60;

// Move all objects based on elapsed time
Vector2u direction = normalize(player.getPosition() - enemy.getPosition());
enemy.move(delta * speed * direction);

      

By the way, basic knowledge of linear algebra is very often needed in game development, so you can pay to attend an online course.

+3


source


You have to account for the elapsed time (since the last frame) - dt - in your calculation.

The enemy has a set speed: the enemy.

I will not use the move () function, but SetPosition ().



You need to calculate the new position of the enemy:

enemy.x += dt * enemy_velocity * cos(angle);
enemy.y += dt * enemy_velocity * sin(angle);

      

And influence it with SetPosition ().

0


source







All Articles