# How can AI compute movement in 2D games

I know how to create a basic AI for a game, where the AI simple creates units that only march forward. The AI only decides when to create a new unit, taking into account a number of considerations.

But now, I'm working on a game where the user controls a spaceship that can move in any of 8 directions (up, down, left, right, and any of the 4 diagonals).

The user is battling another spaceship that moves in the same way. The spaceships can shoot missiles. The missiles fly in the direction the shooting-spaceship is facing.

I need to program the AI, but have no idea how to make such an AI. Could you give me some general direction on how to make an AI that computes it's movements on the screen?

I have some very general idea, I would also like to know if this is somehow a decent direction:

The AI ship always tries to get inside a specific radius from the user's ship. Once it does, it moves up, down, left, or right to a point where it will be able to hit it's opponent. Then it shoots a missile in the direction of the user's ship.

Is this a decent direction? Any ideas or places where I can get started learning these things? My main concern is how the AI will compute it's movements.\

EDIT: Both the enemy ship and the player's ship can face any direction.

Thanks

• This is a really broad question, so as it is I'll vote to close. However the general idea you propose is a decent direction, so give that a try. If you have trouble implementing that, then ask about that. If that approach doesn't give the behavior you want, then try something else. Jan 27, 2014 at 12:23
• Don't close, there is a legit question here, he has a goal as to what he wants to achieve. Give him some time to formulate himself better.
– Herp
Jan 27, 2014 at 12:46
• Are you constrained to a grid? Does the AI know where the player is, or should the AI 'explore' the game field? Do you need to predict where the player is going, or is a simple 'straight towards' strategy (heuristic) sufficient? Should the AI try to not get hit? That's a few questions for you :) Jan 27, 2014 at 13:58
• Here's a book for answering this question and bunch of follow-on questions: amazon.com/Programming-Game-AI-By-Example/dp/1556220782 Jan 27, 2014 at 14:04

Take the players ships position, and subtract it with the enemy ships postion. The resulting vector is the vector the enemy has to travel to reach the player ship. You can use this vector to travel the enemy ship within the specified radius of the player ship.

Like so:

vec4 playerPos = player.position;
vec4 enemyPos  = enemy.position;
vec4 toPlayer  = playerPos - enemyPos;

float distance = (((toPlayer)^2)^(1/2)); //don't kill me if I got this wrong