Page 1 of 1

How do you calculate shooting vector [Solved]

Posted: Sun Jan 19, 2020 2:52 pm
by axehigh
I am making a shoot'em up game, where the enemy is shooting at the player (or a target coordinate)

How do you make the bullet fly in a straight line at the player, when f.ex the shot source coordinates are at 300,300 and the player is at coordinates 500,500?

Re: How do you calculate shooting vector

Posted: Sun Jan 19, 2020 3:03 pm
by raidho36
Math function "atan2" calculates angle based on coordinates to the target (from 0,0).

Re: How do you calculate shooting vector

Posted: Sun Jan 19, 2020 9:40 pm
by pgimeno
You don't need atan2 for that though. You can use the vector length formula:

Code: Select all

local function vector_length(x, y)
  return math.sqrt(x^2+y^2)
end
Now, the vector from the enemy to the player is given by (player - enemy), that's player.x - enemy.x, player.y - enemy.y. Divide that by its length:

Code: Select all

local vx = player.x - enemy.x
local vy = player.y - enemy.y
local vlen = vector_length(vx, vy)
vx = vx / vlen
vy = vy / vlen
and you have a unit vector pointing from the enemy to the player. Multiply that by dt times the bullet speed, and voilà.

Re: How do you calculate shooting vector

Posted: Sun Jan 19, 2020 11:37 pm
by axehigh
Thanks!

Worked like a charm