If my object is certain distance away from another do something?

Hey guys,
Im trying to to get my objects to deactivate when its a certain distance away from the player in x axis, which in my game is behind the player. the current code doesnt seem to work.

if(Vector3.Distance(transform.position, Player.playerSelf.transform.position) < 5)
		{
			switch(whoAmi)
			{
			case objType.obstacleA:
				Manager.instance.obstacleA.ReleaseElement(gameObject, true);
				break;	
			case objType.obstacleB:
				Manager.instance.obstacleB.ReleaseElement(gameObject, true);
				break;	
			case objType.obstacleC:
				Manager.instance.obstacleC.ReleaseElement(gameObject, true);
				break;	
				
			}

the problem is in the “if(Vector3.Distance(transform.position, Player.playerSelf.transform.position) < 5)”
but i cant work out what it should be?

If anyone could help i would appreciate it very much.
Thanks

try this if(Vector3.Distance(transform.position, Player.playerSelf.transform.position) > 5)

thanks for the reply, ive tried that doesnt seem to work..

what exactly isnt working, is it throwing an error?

put this line after the { Debug.Log("Distance is more than 5!!!!!!!"); if you see something pop up in your console then then is nothing wrong with the code i posted. if you don't then one of the parameters might not be set right, namely the player.playerself. or you really aren't more than 5 metres away. is this a 2d game or something?

well they are spawning, its just they get destroyed immediately because they start more than 5 meters away. this line basically ensures that they start at least 10 meters away (playerX.x + Random.Range(10.0f,40.0f)); try changing 5 to 50

1 Answer

1

Use this instead, it will work and is more efficient:

if((transform.position - other.position).sqrMagnitude > distance * distance){}

what this does is create a new vector representing the distance between the two original vectors and then compares it’s magnitude squared to your desired distance squared.

In videogames, it is common practice to use distance squared because it is calculation intensive to estimate square roots, which is how square roots work on a computer.

Thanks for that, seems to work now