Calculating the perpendicular direction an AI ship needs to face to fire its cannons?

Hello,

I am creating a battle ship type game. I have programmed the enemy ships so they pursue me if they are close enough. How would i go about programming the ships, so that when they get a certain distance closer to me, they turn 90 degrees to fire their cannons and the direction of the player controlled ship?

many thanks

This needs just a few steps to prepare alignment.

First, check whether the target is within range:

public float targetingRange = 50.0f; // Maximum targeting range

// ...

void Update()
{
	if((player.transform.position - transform.position).sqrMagnitude < targetingRange * targetingRange)
	{
		// Perform action here
	}
}

(This can be further elaborated on by adding an “ideal” targeting range, but makes it that much more involved to implement)

Second, determine whether the target is to the right or left. Not knowing whether your example is a 2D or 3D game, I’ll offer a generalization for 3D:

public float maxFiringAngle = 2.5f; // Degrees' range to fire -- will be half of its total range

if((player.transform.position - transform.position).sqrMagnitude < targetingRange * targetingRange)
{
	Vector3 toTarget = player.transform.position - transform.position;
	toTarget.y = 0; // Flatten to a 2D plane
	float currentAngle = Vector3.Angle(transform.forward, toTarget);
	if(currentAngle < maxFiringAngle)
	{
		// Fire!
	}
	else
	{
		float testRL = Vector3.Dot(toTarget, transform.right);
		if(testRL > 0.0f)
		{
			// Target is to the right, so turn left
		}
		else
		{
			// Target is to the left, so turn right
		}
	}
}

It’s a little bit generalized, but hopefully this may prove sufficient to get you started.

If you’re comfortable making it more complicated, you can factor in the maximum range to begin turning (scaled by their speed relative to the player’s. They’d be more aggressive if significantly faster than you), then an ideal range to fire from (at this point, attempting to travel the same direction as the player while maintaining some distance). Beyond that, there’s trajectory predictions and target leading to influence how they aim toward the player, as well as specifically attempting to get into positions around the player where the player can’t aim, but they can.

This is absolutely perfect, thank you so much!