Click here to Skip to main content
15,924,507 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am made rows for each gameobject that I spawn in to go down and if they are within range of an enemy, they will attack that enemy and then keep going. But the rows are close so if I have the range of the Gameobject too big then they will attack the other enemies in the rows next to them once they come within range. If both players are in the same row they have the same z position and so what I want to do is, if they have the same z position, they can attack each other, if not, then they can't attack.

What I have tried:

C#
float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);


thats what I tried for getting the distance and it works, its just I want it to be more of a box range rather than a sphere range.

C#
if (nearestEnemy != null && shortestDistance <= range && transform.position.z == nearestEnemy.transform.position.z) {
			target = nearestEnemy.transform;
			inRange = true;
		} else {
			target = null;
			inRange = false;
		}


and thats what I did to make the player shoot only the enemies that have the same z position as it, but it didn't work, or doesn't work all of the time
Posted
Comments
Richard Deeming 17-Feb-17 10:35am    
At a guess, you're trying to compare two floating-point numbers which are close, but not equal.

Try replacing the equality check with a range:
Math.Abs(transform.position.z - nearestEnemy.transform.position.z) < MaximumDifference

(Where MaximumDifference is a constant representing the maximum difference you want to allow.)
Member 13006389 17-Feb-17 16:58pm    
OH MY GOD, you are a life saver...I've literally been trying to get this for over a day and a half now and I've been looking up everything. I am not a very good programmer so I don't really understand that Math stuff unless I look it up on the forums. But thank god you came along....Thank you so much!
Karthik_Mahalingam 17-Feb-17 23:57pm    
Always use  Reply   button to post comments/query to the concerned user, so that the user gets notified and respond to your text.

1 solution

the solution was the first comment
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900