Search code examples
callegroallegro5

Creating a projectile trajectory in Allegro


I'm developing a 2D game in C using Allegro 5, where an enemy from a fixed position shoots a projectile at the player's current position. I know I will have to calculate the tangent of an imaginary triangle based on the player's position and the enemy's. However, how can I have the projectile follow a straight line based on that value?


Solution

  • This is a situation where can be easier to work with vectors than angles.

    Some simple math computes the vector between the enemy and the player:

    # Compute the x and y displacement from the enemy to the player
    dx = player_x - enemy_x
    dy = player_y - enemy_y
    
    # normalize the displacement to get the direction vector 
    distance = sqrt(dx * dx + dy * dy)
    projectile.dir_x = dx / distance
    

    ```

    The projectile just needs to follow that vector during the update loop:

    projectile.x += projectile.dir_x * projectile.speed * time_elapsed
    projectile.y += projectile.dir_y * projectile.speed * time_elapsed