Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How can I check if a node is outside the area of a circle and delete it?

Discussion in 'Scripting' started by lixi19821982, Aug 29, 2023.

  1. lixi19821982

    lixi19821982

    Joined:
    Aug 16, 2023
    Posts:
    9
    Hi so, I've written a script that picks 201 random points in a 200 x 200 square. How would I go about checking whether one of these points are outside of a circular area and delete it as shown in the image below?

    Code (CSharp):
    1.  
    2. int xSize = 200;
    3. int zSize = 200;
    4. nodes = new Vector3[(xSize + 1) *(zSize + 1)];
    5.  
    6. for (int x = 0; zSize + 1 > x; x++)
    7. {
    8.     nodes[x] = new Vector3(Random.Range(0, xSize), 0, Random.Range(0, zSize));
    9.  
    10. }
     

    Attached Files:

  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,834
    So, first off, it looks like you want to reject random points that fall outside the circle of radius xSize. You could calculate the distance from one point to another, and if that distance was greater than your circle's radius, you could reject it. Since your vectors are centered at zero, you can just take the magnitude of the vector:
    if (nodes[x].magnitude > xSize) { ... }
    (since the magnitude of a vector point is just the distance that point is from zero).

    But it's possible I read too much into your code and question, and you might just want to pick points that are inside the circle. The UnityEngine.Random class has a static property, Random.insideUnitCircle, which is perfect for this task. Instead of picking a random X and a random Z, pick a random Vector2 inside the unit circle, scale it by your desired radius, and convert it to Vector3 if you like.
     
    Yoreki likes this.
  3. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    I think the Random.insideUnitCircle mentioned by @halley is what you are looking for to generate random points inside a circle (instead of a square). However, if you can give a bit more context about the problem you are trying to solve we may be able to offer more specific solutions, and exclude potential XY Problems.
     
  4. lixi19821982

    lixi19821982

    Joined:
    Aug 16, 2023
    Posts:
    9
    Random.insideUnitCircle worked great, thanks for your help.