Problem
How can i find the direction of one rectangle w.r.t to the other. The directions i am interested is up, down, left, and right. My rectangle is represented by a Cell class. I am trying to write a function in that cell class. Function accepts a parameter of Cell type the returns the direction either 1(up) 2(down) 3(left), or 4(right) of the passed cell w.r.t to the calling cell.
What i tried
I found the mid point of both the rectangles, and then compared the x, and y coordinates. But this technique is not working in all the cases. whenever i find a missing case, i have to include more and more if statements which i think is not a good programming practice. its becoming more and more error prone and difficult to understand.
While searching for the solution: maybe math.atan2() can work in my case. Maybe i can find the angle between mid points of these 2 rectangles and use the value of angle to determine the direction. But i am not sure if my thinking is correct.
Please guide me. Should i keep using my function and rectify it, or is there a better solution such as math.atan2()? A helping image for better understanding and a required solution is demonstrated below after the code.
Code
public int dirOfThisCell(Cell cell)
{
int dir = 0;
//find mid points of both cells
PointF midPointThis = this.computeAndGetMidPoint();
PointF midPointCell = cell.computeAndGetMidPoint();
//MessageBox.Show(mess);
//if x of both points is same or with little variance because of variance in sizes of cells
===>> //Comparison Starts!!
if (midPointThis.X > midPointCell.X)
{
//this cell is to the right.
if ((midPointCell.Y) == (midPointThis.Y))
{
dir = 3;
}
else if (Math.Abs(midPointCell.Y) - Math.Abs(midPointThis.Y) < 5) { dir = 3; }
else if (Math.Abs(midPointCell.Y) - Math.Abs(midPointThis.Y) > 5) {
if (midPointThis.Y > midPointCell.Y) { dir = 1; }
else if (midPointThis.Y < midPointCell.Y) dir = 2;
}
// a considerable difference
else { dir = 3; }
//some small variations in y
//else if(Math.Abs()
}
else if (midPointThis.X < midPointCell.X)
{
// this cell is to the left
if ((midPointCell.Y) == (midPointThis.Y))
{
dir = 4;
}
else if (Math.Abs(midPointCell.Y) - Math.Abs(midPointThis.Y) <= 10)
{
dir = 4;
}
}
//if this cell is below
else if (midPointThis.Y > midPointCell.Y)
{
//this cell is down than the cell
if ((midPointCell.X) == (midPointThis.X))
{
dir = 1;
}
//else if (Math.Abs(midPointCell.X) - Math.Abs(midPointThis.X) < 2) { dir = 1; }
}
else if (midPointThis.Y < midPointCell.Y)
{
if ((midPointCell.X) == (midPointThis.X))
{
dir = 2;
}
}
return dir;
}
Image
Sample Image
Sample rectangles are shown in the picture number wise. The rectangle can be of single cell or made by combining multiple numbered cells.
Sample Solution required
Direction of cell 18 w.r.t to 8 should be up(1)
Direction of cell 18 w.r.t to 10 should be up(1)
Direction of cell 14 w.r.t to 13 should be right(4)
Direction of cell 9 w.r.t to 31 should be down(1)
Direction of cell 15 w.r.t to 9 should be left(3)
I am working in c#.
Any help would be much appreciated.
Thank You
Calculating the angle of the center of a rectangle compared to the center of another does not seem to be a very good idea, because the center of those rectangles are only telling you where their center is and the solution is completely reluctant to the width, height and direction of the sides. I know that the third one is not a concern in your specific case as you can safely assume that the sides are horizontal XOR vertical, but in general terms, that could be an issue as well. To calculate the relative position of Shape1 (which is a rectangle in our particular case) compared to Shape2, you need to calculate the minimum and maximum x and y for both.
Shape1 is to the left of Shape2 <=> Shape1.maxX <= Shape2.minX
Shape1 is to the right of Shape2 <=> Shape2.minX >= Shape2.maxX
Shape1 is above Shape2 <=> Shape1.maxY <= Shape2.minY
Shape2 is below Shape2 <=> Shape2.minY >= Shape1.maxY
Related
Hi im building a chess game in Unity and my issue is that the queen can move above a friendly piece.
When a piece is selected, an array of legal moves on the board is generated
legalMoves = piece.Move();
I chose to work with vectors here so any move within the list is a 2d Vector.
Then in a loop, I check if any of the moves are within the boundaries of the board and if the move would place the piece on another friendly piece. If it does, then discard that move but my problem is that it should discard all the moves within that direction.
For example: if the queen is on (3,3) and there is a pawn on (3,5), then all the moves (3,6), (3,7) ... should be discarded but not (3,4).
Similarly, if the black queen is on (7,7) and a pawn is on (7,5) then all moves (7,4), (7,3), (7,2) .. should be discarded but not (7,6).
My intuition here was that when a vector has a friendly piece on it, check the direction and the length of all my legal moves against it:
if (dir.normalized.Equals(temp[j].normalized) && dir.SqrMagnitude() < temp[j].SqrMagnitude())
The idea was to remove all the vectors from the legalmoves with the same direction but with greater length, however this doesn't really seem to work because the normalized vectors will not be equal.
Here is the relevant code
foreach (var dir in legalMoves)
{
if (0 <= dir.x && dir.x <= 7 && 0 <= dir.y && dir.y <= 7)
{
//TODO shrink this to 1d array search
if (board[(int) dir.x, (int) dir.y].getPiece() == null)
{
Instantiate(trail, dir, Quaternion.identity);
}
else
{
List<Vector2> temp = legalMoves.ToList();
GameObject[] trails = GameObject.FindGameObjectsWithTag("bullet");
for (int j = 0; j< temp.Count; j++)
{
if ( dir.normalized.Equals(temp[j].normalized) && dir.SqrMagnitude() < temp[j].SqrMagnitude())
{
foreach(var t in trails)
{
// remove trail
if (t.transform.position.Equals(temp[j])) Destroy(t);
}
// remove the move with the same direction
temp.Remove(temp[j]);
}
}
temp.Remove(dir);
legalMoves = temp.ToArray();
}
}
}
here is my problem visualized chess collision issue
Ok, maybe there could be a better solution, however, the way I managed to do it is the following:
Our queen = q is at (3,0) , obstructed piece = k is at (3,6),
If we calculate the offset from k to q we always get an axis which is 0 (either x or y ) in this case it is x.
Since we know an axis is 0 we can check which one is 0 using a boolean, in this case it is x, and simply discard all the legal moves which are on x and above 6 or below 6 for black pieces.
I haven't thought about how to do it if a piece obstructs horizontally, however I'm sure its just a matter of adding/ substracting the right coordinates as above.
Actually my robot wants to move from source to target with obstacle avoidance. I find out the obstacle(rectangle shape) and Target(circle shape) in pixels. But i don't know how to find the path from source to target... Please help me.
Here is the code for finding obstacle and target.
for (int i = 0, n = blobs.Length; i < n; i++)
{
List<IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
AForge.Point center;
float radius;
// is circle ?
if (shapeChecker.IsCircle(edgePoints, out center, out radius))
{
g.DrawEllipse(whitePen, (float)(center.X - radius), (float)(center.Y - radius),
(float)(radius * 2), (float)(radius * 2));
target.Add(center.ToString());
}
else
{
List<IntPoint> corners;
// is triangle or quadrilateral
if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
{
// get sub-type
PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);
Pen pen;
if (subType == PolygonSubType.Unknown)
{
pen = (corners.Count == 4) ? redPen : bluePen;
}
else
{
pen = (corners.Count == 4) ? greenPen : brownPen;
}
g.DrawPolygon(pen, ToPointsArray(corners));
}
}
}
This above coding will detect obstacle and target position pixel values and store it in a seperate array. But from these pixel values how to calculate the path? Waiting for ur suggestions.....
Trying looking up the A* search algorithm.
I have not looked into your code but it is a classic path finding problem. One suggestion could be to map the entire area the robot moves onto a grid. The grid can have discrete cells. And then you can use any graph search algorithm to find a path from start cell to goal cell.
You can use few of the algorithms, like Dijkistra, Best-first and A-Star search algorithms. It turns out that A-Star is efficient and easy to implement. Check this, contains a nice explanation about A-Star.
This question already has answers here:
What is the fastest way to find the "visual" center of an irregularly shaped polygon?
(15 answers)
Closed 9 years ago.
what algorithm that i can use to get the center of polygon (red point)
case 1 : i try with maxX, maxY, minX, minY and i got the wrong point (black point)
case 2 : i try to get the second max and min coordinate X and Y, but i got problem with the polygon which have point less than 5
case 3 : i add if point count < 5 then use case 1 else use case 2 but i got some error for some polygon
can you tell me the right algorithm for me??
note :
explaination for 4th picture
//ma mean max, mi mean min, X1 mean first, X2 mean second
maX1 = maX2 = maY1 = maY2 = 0;
miX1 = miX2 = miY1 = miY2 = 2000;
//aCoor is array of coordinate, format = {x1,y1,x2,y2,x3,y3,x4,y4,...}
for(int i=0; i<aCoor.count(); i+=2)
{
//point is list of point
point.Add(aCoor[i],aCoor[i + 1]);
//this to get second max X
if(maX2 < aCoor[i])
{
maX2 = aCoor[i];
//this to get first max x
if(maX1 < maX2) {maX1 += maX2; maX2 = maX1 - maX2; maX1 -= maX2;}
}
//this to get second min X
if(miX2 > aCoor[i])
{
miX2 = aCoor[i];
//this to get first min x
if(miX1 > miX2) {miX1 += miX2; miX2 = miX1 - miX2; miX1 -= miX2;}
}
//this to get second max Y
if(maY2 < aCoor[i + 1])
{
maY2 = aCoor[i + 1];
//this to get first max x
if(maY1 < maY2) {maY1 += maY2; maY2 = maY1 - maY2; maY1 -= maY2;}
}
//this to get second min Y
if(miY2 > aCoor[i + 1])
{
miY2 = aCoor[i + 1];
//this to get first min x
if(miY1 > miY2) {miY1 += miY2; miY2 = miY1 - miY2; miY1 -= miY2;}
}
}
if(point.Count < 5)
{
Xcenter = (maX1 + miX1) / 2;
Ycenter = (maY1 + miY1) / 2;
}
else
{
Xcenter = (maX2 + miX2) / 2;
Ycenter = (maY2 + miY2) / 2;
}
this how far i do
What you are looking for is not the geometric center (or centroid) of the polygon, but the center of the portion of the polygon's axis of symmetry which lies inside the polygon. Let me edit one of your examples to demonstrate:
Edited example
Do you see what I mean?
I picked this example because it demonstrates another flaw in your thinking; this is two polygons, and each of them produce a point that fits the qualifications you're looking for. In your example you just arbitrarily chose one of them as the point you want. (I have seen your edited fourth example; it still has two interiors and does not change my point.)
In any case, what you're looking for is actually the solution to two problems: first, how to find an axis of symmetry for a polygon; second, finding a line segment on that axis of symmetry which also lies in the interior of the polygon. After that, finding the center of that segment is trivial.
I can't post any more links, but there's a paper by P. Highnam out of Carnegie Mellon University entitled Optimal Algorithms for Finding the Symmetries of a Planar Point Set which could help with the first problem, it's a bit involved so I won't explain it here. The second problem just boils down to testing each line segment to see if it contains a point of intersection with a line along the axis of symmetry running through the figure's centroid. Assuming your polygon only has one interior (read: is not like your fourth example), you should get two points. Average them and you have your center.
I'm working on a project i need to find coordinates of pixels of selected area. I'm gaining this coordinates by simply clicking on a C# picture box. I need to find the pixel coordinates of the gray area as show in the picture in order to change the color of this ash area. is there a defined method in C# do do this? or please on how to archive this.
code samples will appreciated.
thanks in advance.
Selected Coordinates
Required Area
What you need is a point-in-polygon algorithm ( http://en.wikipedia.org/wiki/Point_in_polygon )
static bool PointInPolygon(Point p, Point[] poly)
{
Point p1, p2;
bool inside = false;
if (poly.Length < 3)
{
return inside;
}
Point oldPoint = new Point(poly[poly.Length - 1].X, poly[poly.Length - 1].Y);
for (int i = 0; i < poly.Length; i++)
{
Point newPoint = new Point(poly[i].X, poly[i].Y);
if (newPoint.X > oldPoint.X)
{
p1 = oldPoint;
p2 = newPoint;
}
else
{
p1 = newPoint;
p2 = oldPoint;
}
if ((newPoint.X < p.X) == (p.X <= oldPoint.X)
&& ((long)p.Y - (long)p1.Y) * (long)(p2.X - p1.X) < ((long)p2.Y - (long)p1.Y) * (long)(p.X - p1.X))
{
inside = !inside;
}
oldPoint = newPoint;
}
return inside;
}
(from http://www.gamedev.net/topic/533455-point-in-polygon-c-implementation/ )
You may also use the .Net HitTestCore Method if you use System.Windows.Shapes.Polygon to represent your polygon. I can't tell how easy that will work though.
Use the Click event, and pull out the mouse coordinates from the event. If the gray area is defined by a function, you can write a method to check if it's within the area specified. If not (it's just a static image), you should use the mouse coordinates to calculate which pixel you have clicked, and check its color value. There might be a method to get the color value where the mouse clicks (however, I might be confusing the method with the glReadPixel method in OpenGL).
I want to move through the pixels of an image, not by going line by line, column by column in the "normal" way. But begin at the center pixel and going outward in a spiral motion. But I'm not sure how to do this.
Any suggestions on how this can be done?
You can do this by using parametric functions, function for radius is r(t) = R, and x(t) = Rcos(t) and y(t)=Rsin(t).
Do you mean something like this?
It would be helpful to think about this in reverse.
For example, starting at the top left corner and moving in a clockwise direction you would move along the top row, then down the right hand side, along the bottom, and up the left edge to the pixel under the starting point.
Then move along the second row, and continue in a spiral.
Depending on the dimensions of the image you will end up with either a single column of pixels or a single row of pixels and will be moving either up/down or left/right.
From this finishing point you can then follow your steps backwards and process all the pixels as you need to.
To work out your starting position mathematically you would need to know the width/height of the image as well as which pixel you would like to end on and the direction you want to be travelling in when you get to the last pixel.
Something like this should do it:
int x = width / 2;
int y = height / 2;
int left = width * height;
int dir = 0;
int cnt = 1;
int len = 2;
int[] move = { 1, 0, -1, 0, 1 };
while (left > 0) {
if (x >= 0 && x < width && y >= 0 && y < height) {
// here you do something with the pixel at x,y
left--;
}
x += move[dir % 4];
y += move[(dir % 4) + 1];
if (--cnt == 0) {
cnt = len++ / 2;
dir++;
}
}
If the image is not square, the spiral will continue outside the coordinates of the image until the entire image has been covered. The condition in the if statement makes sure that only coordinates that are part of the image are processed.