Top Down 2d (PC): Targeting code optimisation

Hello,

Thanks for reading. I’m fairly new to optimisation, and I’ve recently been doing some stress testing on the game I’m working on, which is a 2d top down shooter for PC. There could potentially be up to 7 turrets and maybe more than 40 enemies in game at once. I’m getting drops to around 40 fps in the editor mode with 4 turrets. I’m aware 40 is still quite high, but my comp, although a few years old is fairly decent, and I’d like the game to run on lower end hardware.

I think one of the problem areas may be the code turrets use to target enemies. The code for targeting (which I’ve posted below) is called once per update while an enemy is in the the turret’s range (trigger) collider. Can anyone advise me whether calling this up to 7 times per update is chewing up CPU time? Is there any way this could be optimised, or called less, without detracting from the accuracy?

// Check that the target is still in range 
float targetDistance = Vector3.Distance(target.transform.position, transform.position);
				
if(targetDistance <= (attackRadius + 1)) 
{
	// Get target's transform.position
    targetPosition = target.transform.position;
					
	// Rotate to Target
	RotateTurret();
}

The RotateTurret() method

// Get current velocity of target
Vector3 targetMovePerSec = target.rigidbody.velocity; // since you physics to move
targetMovePerSec.y=0; 
		
// Predict the future position of the target
Vector3 estHitPos = targetPosition + targetMovePerSec * secsFlightTime;	
		
// Get the rotation needed to hit the enemy
Vector3 aimDirection = estHitPos - bulletSpawn0.transform.position;
		
// Rotate turret to face that position
Quaternion neededRotation = Quaternion.LookRotation(aimDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, neededRotation, rotationSpeed * Time.deltaTime);

I’m considering the idea of making the bullets fired by turrets homing, so the turret will only have to be facing roughly in the direction of the enemy, but this will require more calculations in the bullet script. Can anyone offer me some advice on a good way to deal with this? Thanks!

Have you solved this problem ? I am creating a space shooting top down game. Could you share this script with me ? It would help me a lot. Thanks bro. @DMCH