To check if the bullet is currently inside a player, you can test the distance between the player and the bullet. If they are closer together than the radius of the player circle, then the bullet is inside the player.
for each player
for each bullet
for each OTHER player
if (distance between bullet and player < radius of player)
// score a hit
// destroy the bullet or note that it shouldn't damage this player again
I do not recommend that method, though. The bullet travels some distance, let's call that A
, each update. If A
is larger than the width of the target player at the point where the bullet's path crosses it, then the bullet could "tunnel" through the player between frames. Since a bullet could just clip a little sliver at the edge of a player, this is possible even with fairly slow-moving bullets and players.
Instead, I would check if the bullet's path has intersected the player object during the last frame. It's more complicated, but it is a fairly optimal process that shouldn't be noticeably slower than the less accurate method.
// for each player
// for each bullet
// set up some variables
var x0 = bullet.playerX;
var y0 = bullet.playerY;
var radians = bullet.attack * Math.PI / 180;
var dX = bullet.traveled * Math.Cos(radians);
var dY = bullet.traveled * Math.Sin(radians);
var sShotSqr = bullet.traveled * bullet.traveled;
// you'll need to track the last bullet position, or integrate this code
// into the bullet update code so you can use both the previous and
// current 'traveled' values.
var tMin = bullet.traveledPrev / bullet.traveled;
// for each OTHER player
var dXTarget = playerArr[k].x - x0;
var dYTarget = playerArr[k].y - y0;
var t = (dXTarget * dX + dYTarget * dY) / sShotSqr;
// check for the bullet moving away from the player
if (t < 0)
continue;
var radius = playerArr[k].radius;
var deltaTMax = radius / bullet.traveled;
// check coarsely for the player and bullet not crossing paths this frame
if (t + deltaTMax < tMin || t - deltaTMax > 1)
continue;
var xSpoke = x0 + dX * t;
var ySpoke = y0 + dY * t;
var offsetSqr = radius * radius - xSpoke * xSpoke - ySpoke * ySpoke;
// check for the bullet's path not touching the player
if (offsetSqr < 0)
continue;
var deltaT = sqrt(offsetSqr / sShotSqr);
// check for the bullet not yet reaching the player or the player
// moving across the path after the bullet has passed
if (t + deltaT < tMin || t - deltaT > 1)
continue;
// score a hit
Caveat: I wrote this up here on the site, so it probably contains syntax errors. There may be transcription errors also - x instead of y or something like that.
The process is pretty straightforward, though it's a bunch of code. It calculates the little segment of the player's circle that crosses the bullet's path, then checks whether the bullet has touched that segment during the time since the previous update.