C#: 2D sub-Tile Line intersection - c#

I have some problems getting an algorithm for my game to work and hope someone here can help me. Google didn't seem to be a good help as most solutions just work for full tiles.
In the game units can occupy different positions inside a tile, i.e. they can be in the upper left corner, center, bottom right, ... position of tile (2/3), i.e. (2.2/3.1), (2.5/3.5), (2.8/3.9).
If they move from position (2.2/3.1) to (5.7/4.1) i require a check to see if there is an obstacle in the path.
My current algorithm is:
Starting from (2.2/3.1)
Calculate the angle of the movement (i.e. 70 degree)
Move 0.1 steps in that direction
Check which tile i'm on (floor(p.X)/floor(p.Y))
Repeat from 2
This algorithm works but to me it doesn't look very efficient as an obstacle can be only a full tile, not a part of a tile (units don't collide). If i increase the step size i begin to miss tiles that are only crossed slightly (i.e. you only cross the lowest left corner). Even with a step size of 0.1 it's still possible to miss an obstacle.
I tried to find a solution to take the sub map (all tiles with the corners (floor(start.X)/floor(start.Y)) and (ceil(start.X)/ceil(start.Y)), move through every tile and check mathmatically if it gets crossed. Sadly i seem to lack the required math knowledge for this check.
My last idea was to take all 4 borders of a tile as a line and do line-intersection but that seems to be slower than my original approach.
Any hints?
Thanks.

Instead of tracing the path by stepping along the line - you want to jump right to the next possible tile (the border). This can be calculated fairly simply. I will use your sample numbers above.
Calculate the line eqn (y= .286x + 2.471)
You are starting on tile 2,3 and moving towards tile 5,4. So calculate the y value when x goes to 3 (the border to the tile immediately to the right). It is 3.329.
Then calculate the x value when y goes to 4 (the border to the tile immediately above). It is 5.346.
Starting at 2,3 and moving right gets to 3,3.329. Moving up gets to 5.346,4. You intersect on the right(moving 2 -> 3 on x doesn't move a tile on y). You don't intersect above until you are on tile 5 in the x.
The tile calculated in 4 becomes your new comparison (3,3). Repeat from step 2.
This process only incurs one calculation per tile moved (regardless of your precision or how big the tiles are) and is exact. Note that the values calculated can be stored and reused instead of blindly calculating both intersections over and over. In the above we know (step 4) that we don't move up a tile until x=5. So the entire path can be inferred without another calculation (2,3 -> 3,3 -> 4,3 -> 5,3 -> 5,4).
It is also possible to precalculate all the transistions instead of doing them stepwise although this would only be beneficial if you always need the entire path (you don't since you want to stop processing once you find an obstacle).
Two caveats. Be careful about signs and which way the line is going - many a bug happen by not paying close attention to negative slopes. Also, using reals you almost never will cross diagonally (two borders at once) but you should be aware of it (handle it in the code) just in case.
There is a name for this method but I can't remember it off the top of my head. I believe it might be from Game Programming Gems series but maybe someone else can provide a better reference.

Related

How to check the highest object's highest point on the y axis

I'm still making the game about tower building using Unity and now I have problem that have haunted me for about week now.
Game mechanic for losing is that there is line which goes up at a certain speed and when it goes above the tower, game should end. I'm wondering is there any way of checking highest objects highest point(because of rotated objects and irregularly stacked objects)?
There's a few ways to achieve this:
1) You can shoot a bunch of rays down from high up in the sky. Find all the hit.point positions and then loop through the points and store which building is the highest.
2) Another would be for each block of your building that is added - keep it as a child of an Empty Building gameObject. Then all you need to do is see which Building gameObject has the most children and you know it's the tallest. This assumes all blocks are the same size in Y and then you can easily calculate the height with highestChildCount * blockSizeY
3) Another way to do it would be to use the point in the line that is traveling up. Shoot a ray out of that point to the left and right. If it is hitting a building then the game continues. If it doesn't hit anything the game is over. This is the simpliest as it doesn't require calculation of any heights and your buildings can be made any way you like as long as they have colliders on it for the ray to hit. <--- This is likely the best method for what I'm hearing you asking.
(Note. I might have some spelling mistakes in the naming of methods so proofread before copy-pasting)
Since your are using a line, you might want to find the bounding box of an object. I have never tried the bounding box method so it might not work. The second method uses a little bit of math. If your line is vertical, then finding the highest point is easy. All you need to do is find the y position of the object and add half the y-scale to find the highest point. Note it will only work if the transform origin of the object is at the center. If the origin is at the bottom of the line you will have to add the full y-scale value. If its one third the way up, then only 2 thirds the y-scale value. I think you get the idea. This rule apples for the next condition too. If your line is at an angle, this is where it gets a little bit more complicated. We need to find the absolute value of the rotation in which the line is rotated at. Make sure the line is rotated at less than a 90 degree angle from being vertical. After this, we need to know the length of the line. Imagine a right triangle that the line itself is the hypotenuse, the base is the distance between the farthest left point of the line to the farthest right on the line(or other way around), and the distance from the lowest point of the line to the highest point of the line being the actual height of the triangle. Since we know the angle the line is rotated at and the length of the line, we need to figure out the ratio between the side opposite to the angle that represents the rotation the the hypotenuse(aka the length of the line) and the hypotenuse. This always stays the same if the rotation is the same for all right triangles. Because of this why use mathf.sin(), the rotation of the line. Remember to convert the rotation value(which is stored in degrees) to radians. This can be done by multiplying the rotation value by mathf.deg2rad. Once we know the sin, we multiply the length by the sin value that is outputted. Now we know how long the distance from the bottom to the top of the line is. Again, if the origin is the middle we add the y-position to half the value we get from the previous calculations. If it is in the bottom then the y-position plus the whole value we get from the previous calculations. Same rule as before. I am also quite new to Unity, only a little over a year of experience so there may be fallacies in my answer. Hope it helps. :)

c# how to detect intersecting circles as separate from edgepoints

I am trying to create a 2(or more) circles from a list of edgepoints which is sorted. A egdepoint is just a point. A list of edgepoints make the edge of a circle. Drawing a line between the edgepoints gives the black line in the pictures. So there is no radius and circles can vary in size.
It looks like this:
My idea is to split it like picture 2. Next, create circles like in this article. Ofcourse with the fist, middle and last point.
I created a method to detect whether the edgepoints are sorted clockwise or counter clockwise. Unfortunately I am stuck on how to detect these "split points" The picture can be rotated ofcourse.
The result should be 2(or more) list with edgepoints:
So how can I detect these "split points"? Or is there a better way to detect intersecting circles as separate?
Input: Something like Point[]. Output: Something like List[Circle]
Assume input is sorted by position around the outer edge of some picture that is made up of overlapping circles. Any points in the interior of the picture are not included.
I thought about it more and I think you can find the points easier if you consider slope. Points where the slope varies wildly are the points you are looking for.
[Revised thought - Find the transition points first, then the circles.]
Start by using a function to calculate the slope of a line segment between two points. As you go around a circle, you will have a reasonable change in slope (you will have to discover this by reviewing how close the points are together). Say you have points like { A, B, C, D, ...}. Compute the slope of A->B and B->C. If the points are evenly spaced, that difference or the average difference might be a tolerance (you have to be careful of transition points here - maybe compute an average over the entire set of points). If at some point the slope of K->L and L->M is very different from J->K and K->L then record that index as a transition point. Once you have traversed the whole set (include a test for Y->Z and Z->A as well if it is a closed shape), the recorded indexes should define the transition points. Use the mid-point of each segment as the third point for each circle. (e.g. if you identified I and M as transition points, then use I, K, and M to define a circle).
[Original thought - find the circles first]
Use the referenced article to determine the center of a circle based on three points. Then determine if it is really an interesting circle by testing some of the points around the reference points. (Say, pick every 5th or 10th point then verify with all the interior points). With more overlapping circles, this becomes a less effective process so you will have to define the algorithm carefully. Once you get all the reference circles, process through all of the edge points (assuming these are points on the exterior of the drawing). Using center, radius, a distance formula, and a tolerance, determine which points are on which circle. Points that fit the tolerance on more than one circle are the points you are looking for I think.

Is there an algorithm to generate a graph outline?

I've searched the Internet and maybe I'm missing some correct keywords but I managed to find nothing like this. I only found the poly-lines (or just the lines) which are not exactly the graphs. I would like to generate a graph outline (of radius r) as seen in the picture. Is there something already available? I would like to avoid reinventing the wheel so to speak.
If anyone can at hint me at something or at least at some basic principle how to do it it would be great. Otherwise I'll "invent" one on my own of course.
Optimally in C#.
Update: I need to calculate outline polygon, not just visually draw it. The green points represents the resulting polygon. Also the "inner" holes are ignored completely. Only one outline polygon should be enough.
Update 2: Better picture to show some more extreme cases. Also the edges of graph never overlap so no need to accommodate for that.
Update 3: Picture updated yet again to reflect the bevel joins.
First, for every "line piece" from point A to B, generate the rectangle to it (all 4 points as "path", so to say). Then search two overlapping rectangles and merge them:
Merging is a bit complicated, the idea: Start with calculating the angle of all 8 lines (eg. if the rectangles are traversed clockwise). Then traverse one rectangle until the first line-line-intersection, check with the angles which direction is "outside", and move along the crossing line of the second rectangle ... until you arrive at the start point again => Now you traversed the shape of both together (and hopefully saved it somewhere).
Merge until only one large piece is left (or multiple non-overlapping pieces). In theory, starting from any point, you can traverse the whole shape, but there´s another problem: Holes are possible.
If one shape has two or more disjuct sets of points (where no point from set 2 is reachable from set 1 and vice-versa), all but one disjunct path is of a hole. An easy possibility to get the real outer border is to search for an extremum, ie. the point with the largest or smallest X or Y coordinate (only one of the 4 combinations in enough). This point surely is a part of the outer border.

How to find a shape in a series of mouse clicks?

I was wondering how (if at all) it would be possible to determine a shape given a set of X,Y coordinates of mouse clicks?
We're dealing with a number of issues here, there may be clicks (coords) which are irrelevant to the shape. Here is an example: http://tinypic.com/view.php?pic=286tlkx&s=6 The green dots represent mouse clicks, and the search is for a square at least x in height/width, at most y in height/width and compromised of four points, the red lines indicate the shape found. I'd like to be able to find a number of basic shapes, such as squares, rectangles, triangles and ideally circles too.
I've heard that Least Squares is something that would help me, but it's not clear to me how this would help me if at all. I'm using C# and examples are more than welcome :)
You can create detectors for each shape you want to support. These detectors will tell, if a set of points form the shape.
So for example you would pass 4 points to the quad detector and it returns, if the 4 points are aligned in a quad or not. The quad detector could work like this:
for each point
find the closest neighbour point
compute the inner angle
compute the distance to the neighbours
if all inner angles are 90° +- some threshold -> ok
if all distances are equal +- some threshold (percentage) -> ok
otherwise it is no quad.
A naive way to use these detectors is to pass every subset of points to them. If you have enough time, then this is the easiest way. If you want to achieve some performance, you can select the points to pass a bit smarter.
E.g. if quads are always axis aligned, you can start at any point, go right until you hit another point (again with some thresold), go down, go left.
Those are just some thoughts that might help you further. I can imagine that there are algorithms in AI that can solve this problem in a more pragmatic way, maybe neural networks.

Find smallest irregular polygon from combination of vertices (Performance Critical)

I need to find an irregular polygon with the smallest surface area out of several vertices on a 2D plane.
No this isn't homework. Although I wish I was back in school right now.
There are some requirements on how the polygon can be constructed. Let's say I have 3 different types of vertices (red, green, blue) plotted out on a 8x8 grid. I need to scan all vertices in this grid satisfying the red, green, blue combination requirement and pick the one with the smallest surface area.
Getting the surface area of an irregular polygon is simple enough. I'm mainly concerned about the performance of scanning all possible combinations efficiently.
See the below image for an example. All three types are used to make the polygons however the one circled has the smallest surface area and is my objective.
This scenario is simplified compared to what I'm trying to prototype. The polygons will be constructed of tens if not hundreds of vertices and the grid will be much larger. Also, this will be a process ran 24/7.
I was thinking that maybe I should organize the vertices by type and break them into individual arrays. Then just iterate over the arrays in a tiered fashion to compute the surface area of all combinations. This approach however seems wasteful.
Here is a version based on branch and bound, with some flourishes.
1) Break the grid down into a Quadtree, with annotations in the nodes as needed for the rest.
2) Find the lowest node in the quad tree that has one of each type of node. This gives you a starting solution, which should be at least good enough to speed up the rest of the search.
3) Do a recursive search which takes all possible branches where I say guess, choosing the most promising candidates first where applicable:
3a) Guess a vertex of the least common type.
3b) Using the relative location of points in the quad tree to order your guesses, guess a vertex of the next least common type, so as to guess them in increasing order of distance form the original point...
3z) you have a complete set of vertices.
At each step 3? you have a partial set of vertices, which I presume gives you a lower bound on the area of any complete solution including those vertices (is it the area inside the convex hull of the vertices?). You can discard any partial solutions that are already at least as large as the largest solutions so far. If you can live with an answer that is X% inaccurate, you can discard any partial solutions that are within X% of the largest solution so far. Hopefully this prunes the tree of possibilies you are navigating in (3) far enough to make it tractable.
How about picking the color with the least number of vertices, and checking for each one the immediate neighborhood, if none has the other colors within this neighborhood, increase the stencil size (select next ring around the vertex), and check again. Until at least one of the vertices, has all other colors within the current stencil. If there are more than one, you just need to compare those (simple min reduction) to find the smallest one.
Here's how to find the smallest triangle in time O(n2 log n). Perhaps it will be useful to you.
The high-level idea is to use a rotating sweep-line. At all times we maintain the order of the blue points along the axis perpendicular to the sweep-line, in a binary search tree. When the sweep-line is parallel with the line passing through a red-green pair, we use the BST to find the blue point closest to the red-green line.
As always, we use an event-driven simulation of the sweep-line. For each red-green pair, make one kind of event for its angle. For each pair of blue points, make O(1) of another kind of event for when their relative order changes. Sort all of the events and turn the crank.
If we already have found an area A, we can narrow the search.
The area of a triangle is B*h (base times height).
If you find two points, then B is the distance between them.
Then we can search for a point which is at most A/B (B*h < A => h < A/B) distance from that line. This is the same as searching between two lines parallel to the two points we already have, which are displaced A/B and -A/B.
This should give a complexity of O(n^2*k) where k is the width or height of your grid.
If you don't extract the coordinates you have to do a O(k^5) search, which at least is better than O(k^6) you had to do earlier.
Some more analysis: if p is the probability that a cell contains a vertex then the complexity is: O(k^2p(k^2p(kp))) = O(k^5p^3).
If p=n/k^2, where n is the number of nodes we then get O(n^3/k).

Categories

Resources