c# - How to find closest point (point being (x,y), in a list of different points) to a given point? -
currently have random point being generated random. trying check if given random point close other existing points in plane, if far enough away other points, added list of other points. start 1 given point , first hundered points in list being generated way. problem is, when go draw points on list onto screen, points closer should allowed be.
public void generatefirstmap() { int count = 0; { int randxpixels = main.rand.next(24, main.screenwidth - 16); //leave outer 16 pixels of screen empty (planet sprite has diameter of 8 pixels) int randypixels = main.rand.next(27, main.screenheight - 27); tuple<int, int> coord = tuple.create(randxpixels, randypixels); if (distance(closestpoint(coord), coord) < 200) { continue; } points.add(coord); //list<tuple<int,int>> points; count++; } while(count < 100); public tuple<int, int> closestpoint (tuple<int, int> p1) { tuple<int, int> p2 = tuple.create(0, 0); bool firstrun = true; foreach (tuple<int, int> point in points) { if (firstrun) { p2 = point; firstrun = false; } else if (distance(p1, p2) < distance(p1, point)) { p2 = point; } } return p2; } public double distance(tuple<int, int> p1, tuple<int, int> p2) { vector2 line = new vector2((p2.item1 - p1.item1), (p2.item2 - p1.item2)); return math.abs(line.length()); }
edit: clear, number how close can number threw out there (for now) can >~30
edit2: changed tuples vector2 , used suggested code, still hasn't changed problem
edit 3: using loop loop through points (inside of while loops) , using break seems have fixed problem.
what this?
public void generatefirstmap() { int count = 0; { bool addpoint = true; int randxpixels = main.rand.next(24, main.screenwidth - 16); int randypixels = main.rand.next(27, main.screenheight - 27); (int = 0; < points.count; a++) { int dx = randxpixels - points[a].x; int dy = randypixels - points[a].y; if (dx * dx + dy * dy < 200) { addpoint = false; break; } } if(addpoint) points.add(new point(randxpixels,randypixels)); count++; } while (count < 100); }
just change point class tuple or whatever using
Comments
Post a Comment