0

I've been recreating the classic Asteroids in JavaScript using canvas and am pretty new to game dev. I was wondering is it possible to create an AI that has a 100% success rate of hitting the player (assuming the enemy's bullet can travel indefinitely)? I want to be able to control how accurate the enemy AI can be from completely inaccurate to perfectly accurate - the shot it takes guarantees to hit the player no matter the relative speeds of the enemy and player object.

I have a rough (and simple) example of what I'm looking for on YouTube. As you can see it does a relatively good job of predicting where the player will be next but it is no way perfect (I'm also aware of some bullet speed bugs in that video too, and the UFO shoots in random directions if the player has been destroyed just FYI).

The function I used was this:

function angleBetween( p1, vel1, p2, vel2 ) {
    var relativePoint = {
        x: ( p2.x + vel2.x ) - ( p1.x + vel1.x ),
        y: ( p2.y + vel2.y ) - ( p1.y + vel1.y )
    };

    return Math.atan2( -relativePoint.y, -relativePoint.x );
}

p1 & vel1 being the x,y position and velocity of first object,

p2 & vel2 being the x,y position and velocity of the second object.

So basically is there a way to improve on what I've done so that it will only ever need to take one shot to hit the player taking into account the relative speeds of the objects in question?

Thanks in advance and apologies if I wasn't clear.

ikradex
  • 131
  • 2
  • 5
  • 5
    This is impossible without the computer cheating as the calculation on where to shoot is based on the current velocity and position of player. The issue is that the player can control their velocity after the the enemy has already shot, making the previous final location calculation inaccurate. – thatidiotguy May 20 '13 at 20:14
  • You can fire a bullet that pursuit the player. If the speed of the bullet was higher than player speed it's certain that the bullet will hit. To accomplish that, calculate the vector that points to your player and move the bullet in that direction. Do this every frame so the velocity vector of the bullet will always pointing to player and since you set the speed of the bullet superior than player speed, bang! Player will be hit. – Gustavo Carvalho May 20 '13 at 22:28
  • You can only do that if you force the player to go where the bullet is going. This requires more coordination on the computer's part than simply determining where to aim. There's actually quite a few ways you can do this, most of them would be as thatidiotguy pointed out, be considered outright cheating by the computer. Such as throwing a massive wave of asteroids in just the right pattern to force the player to either hit the asteroids or hit the bullet. Really though it's more simply ensuring that player cannot win at that point. – Nuclearman May 20 '13 at 23:53

0 Answers0