How do you calculate shooting vector [Solved]

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
axehigh
Prole
Posts: 10
Joined: Sat Jan 18, 2020 10:12 am

How do you calculate shooting vector [Solved]

Post 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?
Last edited by axehigh on Sun Jan 19, 2020 11:38 pm, edited 1 time in total.
User avatar
raidho36
Party member
Posts: 2063
Joined: Mon Jun 17, 2013 12:00 pm

Re: How do you calculate shooting vector

Post by raidho36 »

Math function "atan2" calculates angle based on coordinates to the target (from 0,0).
User avatar
pgimeno
Party member
Posts: 3548
Joined: Sun Oct 18, 2015 2:58 pm

Re: How do you calculate shooting vector

Post 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à.
axehigh
Prole
Posts: 10
Joined: Sat Jan 18, 2020 10:12 am

Re: How do you calculate shooting vector

Post by axehigh »

Thanks!

Worked like a charm
Post Reply

Who is online

Users browsing this forum: No registered users and 69 guests