# Select nearest point but sometimes not closest.

Hi im trying to make a enemy bot in my game. But i want it to act like a kinda normal people. With this code below enemy selecting nearest point and move towards to it. How can i make it look like normal person.

``````    void FindClosestEnemy()
{
float distanceToClosestPoint = Mathf.Infinity;
closestEnemy = null;
GameObject[] allPoints = GameObject.FindGameObjectsWithTag("Points");

foreach (GameObject currentEnemy in allPoints)
{
float distanceToEnemy = (currentEnemy.transform.position - this.transform.position).sqrMagnitude;
if (distanceToEnemy < distanceToClosestPoint)
{
distanceToClosestPoint = distanceToEnemy;
closestEnemy = currentEnemy;
}
}
transform.position = Vector3.MoveTowards(transform.position, closestEnemy.transform.position, speed * Time.deltaTime);
speed = 3;

Debug.DrawLine(this.transform.position, closestEnemy.transform.position);
}
``````

Scanning a list and finding the closest distance is how you find it.

Using Mathf.Atan2() can give you a polar direction from cartesian coordinates.

Since thatâ€™s probably about 17 separate steps involving code and scene setup to actually make this all work properly, I suggest you hurry over to Youtube and work through two or three separate tutorials for games that have the kind of mechanic you contemplate.

Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

How to do tutorials properly, two (2) simple steps to success:

Tutorials are a GREAT idea. Tutorials should be used this way:

Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. Thatâ€™s how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

Fortunately this is the easiest part to get right: Be a robot. Donâ€™t make any mistakes.
BE PERFECT IN EVERYTHING YOU DO HERE!!

If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If thereâ€™s an error, you will NEVER be the first guy to find it.

Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

1 Like

Your current code has the player walking directly towards the destination. If you want to make it look more natural, Iâ€™d suggest that your character should start off walking the direction that they are already facing and then you gradually change the direction to face their towards their destination. You could use Vector3.Lerp, but linear interpolation might look stiff. I usually like to grab a simple one-script ease function library for my projects. Something like this:

Animation curves are also really useful for this sort of thing. Then you can just draw your own ease funtion.

1 Like

Thanks for your suggestions and reply sir. I watched a lot of tutorials and videos about game making i almost learn everything from videos and still watching like you said. But i dont know english verywell and there is not much tutorials in my main language. Thats why i just copy paste tutorial codes after i watch them and then try to understand with reading it. But its being problem a lot for example i watched a lot of videos on Randomize something. Yesterday i want it to make my attacks random in x,y seconds. I spent almost 5 hours to do it bymyself without watching a video. If i watch i can understand what the code saying clearly but whenever i want to create code from 0 its being problem

Oh yes how can i make it to move look direction and if we do that doesnt bot move straight to the look position

A cheap way of having a chance to get a not-the-closest-point is adding a random amount to the distance of each point. After â€śdistance=â€ť add a new line: `distance += Random.Range(0.0f, 5.0f);`.

To see how this works, suppose one item is 10 away and another is 12 away. the first item might add 2.5, making it count as 12.5 away. The second item (12 away) wins if it rolls 0.5 or less. Thatâ€™s a 10% chance. Itâ€™s even possible for a 14 to beat a 10, but the 10 has to roll over 4.0 and the 14 still has to roll a very small number.

Obviously, the exact top value of the random roll depends on the normal distance between objects. If the screen is 500 units wide then objects within 10 away are still pretty close, so the random roll could be 0 to 20. Thereâ€™s no reason the lowest number has to be 0, but 0 seems normal â€“ what matters is the range between low and high.

But thereâ€™s one problem with this. The person who wrote that code is super weird and put in a funny hack. sqrMagnitude computes the square of the distance. If one object is 4 away, it says â€ś16â€ť. If the next is 5 away, it says â€ś25â€ť. That makes the numbers extra big in a funny way, making it tough to find a good random amount. I recommend changing it to the more normal â€śmagnitudeâ€ť (if you delete sqrMagnitude and retype the dot, the editor will show that as an option). Itâ€™s a weird hack since sqrMagnitude is to run faster, but they used FindGameObjectsWithTag which is super slow.

BUT, if you want to do much more, stop and just learn programming. Tweaking code you find is fine for a bit, but it gets harder and harder as you change more stuff until itâ€™s faster to learn to code from scratch first. Then you can look at online stuff and say things like â€śOK, that part is basic; that next part is terrible â€“ Iâ€™ll do it my way; oh, wow â€“ that last part is a really good idea I can steal. Good example!â€ť

1 Like

Oh thanks when i added random range to distance it worked. Its not selecting the closest now its really good thanks.

oh lol i wasnt know what sqrMagnitude was. Actually i saw it for first time in this code thanks for warning sir. But i made all the values depends on it and if i change to Magnitude i must rewrite all values so if its not that important for performance can stay like that.

Actually in original code there is no FindGameObjectsWithTag i added myself . Actually i heared in one more place to that is bad for performance but i dont know what can i use instead.Because i instantiate them with colors in other script thats why selecting prefab shouldnt work i guess.
Other point code

``````        float screenX, screenY;
Vector2 pos;

int s = Random.Range(0, coloredCircles.Length);

screenX = Random.Range(minX, maxX);
screenY = Random.Range(minY, maxY);
pos = new Vector2(screenX, screenY);

newPoint = Instantiate(coloredCircles[s], pos, transform.rotation);

spriteR = newPoint.GetComponent<SpriteRenderer>();

float R = Random.Range(0, 226 / 254f);
float G = Random.Range(0, 226 / 254f);
float B = Random.Range(0, 226 / 254f);

spriteR.color = new Color(R, G, B);
points++;
``````

And for programming what did you mean sir. What kind of tutorials i watched C# syntax tutorials and finish one course in udemy about that. Should i watch more or diffrent videos then c# syntax

Thereâ€™s nothing wrong with FindGameObjectsByTag, but eventually itâ€™s easier to put everything you instantiate into your own list as you make them. Then you wonâ€™t need to find them, since there they are.

Iâ€™ve found that unity videos are for fun and not for learning, and the â€śhow to do X with Unityâ€ť stuff doesnâ€™t explain very well, and jumping around between tutorials misses too much. If thatâ€™s working for you, great. But when you get frustrated, find a regular C# book. It should have all the tricks with variables saving things, solving things with nested if, how to use lists and list-loops, and so on, all in one place.