I have an enemy ship and a player ship.
I would like the enemy ship to always fly towards the player in a direct line, at all times, even when the player is moving.
I’m going about this using the Ray class for C# XNA.
I have two vector coordinates, the position/origin of the ray (the players current position), and the Direction of the ray (the enemy’s current position). I’d like the enemy’s position to gradually move towards the players position.
I have this code so far.
enemyPlayerTrack.Position = playerPos;
enemyPlayerTrack.Direction = enemyPos;
I’m unsure whether I need another vector for velocity or not.
In the end, the enemy will be drawn to the screen with a new position with this code:
enemyWorldMatrix = Matrix.CreateTranslation(new Vector3(x, y, z));
Without a mathematical background, I’m having trouble creating a velocity to bridge the two vectors closer and closer.
We choose some speed
s. Then the direction of the player from the enemy is:Overall speed s = sqrt(vel_x^2 + vel_y)^2, so we scale the dir vector to give us the speed:
So now the enemy will always fly at the same speed, directed towards the player. But if the player is near the enemy, the enemy will overshoot and keep bouncing back and forth over the player. So we limit the speed:
This way, by setting the delay, the enemy will slow down as it approaches the player, once it gets close enough to stop moving at its maximum speed (s).