Sign in to follow this  
Whorse

2D Shooter Homing Projectile

Recommended Posts

Hey everyone, I've almost finished a 2D space shooter I'm working on and would like one last piece of advice. I'm busy doing a homing projectile algorithm, and have run into a bit of a problem. At the moment the projectile moves towards the player on the Y axis, but doesn't move in either direction on the X axis.

At the moment I'm doing this every frame:

aMissile.mDirection = new Vector2(mPlayerShip.Position.X - aMissile.Position.X, mPlayerShip.Position.Y - aMissile.Position.Y);

aMissile.mDirection.Normalize();

How would I get it to also move towards the player's X position?

Share this post


Link to post
Share on other sites
At the moment I'm doing this every frame:

Position += theDirection * theSpeed* (float)theGameTime.ElapsedGameTime.TotalSeconds;

As far as I can tell it's the same as your recommendation.

Share this post


Link to post
Share on other sites
You should try something along the lines of this.


float x = (target.X - position.X);
float y = (target.Y - position.Y);
float angle = (float)Math.Atan2(y, x);

Vector2 movement = new Vector2(
(float)(speed * Math.Cos(angle)),
(float)(speed * Math.Sin(angle))
);

position += movement;

Share this post


Link to post
Share on other sites
Like this, assuming missilePos, missileDir, and playerPos are Vector2 and missileSpeed and timeElapsed are floats:


// calculate missile course
missileDir = playerPos - missilePos;
missileDir.Normalize();
missileDir *= missileSpeed;


// update missile position
missilePos += missileDir * timeElapsed;

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this