我正在使用 Allegro 5 用 C 语言开发 2D 游戏,其中敌人从固定位置向玩家当前位置发射射弹。我知道我必须根据玩家的位置和敌人的位置来计算假想三角形的正切。但是,如何让射弹根据该值沿着直线运动?
最佳答案
在这种情况下,使用 vector 比使用角度更容易。
一些简单的数学计算敌人和玩家之间的 vector :
# 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
```
射弹只需在更新循环期间遵循该 vector 即可:
projectile.x += projectile.dir_x * projectile.speed * time_elapsed
projectile.y += projectile.dir_y * projectile.speed * time_elapsed
关于在 Allegro 中创建弹丸轨迹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53105916/