Test if point is within line range on 2D space - java

This question is a bit hard to formulate so I'll start by showing this image:
I want to test if points (such as p1 and p2 on the image) are within the dotted lines that are perpendicular to the line at its limits. I know the coordinates of the points to test and the line's limits.
So for p1 it would be false, and for p2 it would be true.
What would be the most computationaly efficient way to calculate this?
I'm working with floats in Java.

This can be very efficiently done with the dot product:
This is positive if A has a component parallel to B, and negative if anti-parallel.
Therefore if you have a line segment defined by points A and B, and a test point P, you only need two dot product operations to test:
dot(A - B, P - B) >= 0 && dot(B - A, P - A) >= 0
EDIT: a graphical explanation:
The dot product can be shown to be:
Thus if θ > 90 then dot(A, B) < 0, and vice versa. Now for your problem:
In case 1, when dot(A - B, P - B) > 0 we say that P is on the correct side of the dotted line at B, and vice versa in case 2. By symmetry we can then do the same operation at A, by swapping A and B.

If the point to test (tp), together with start point (sp) and end point (ep) of the range, form an obtuse triangle and you can conclude that it is out of range.
https://en.wikipedia.org/wiki/Acute_and_obtuse_triangles
A special case would be tp is same slope as sp and ep, then you calculate the 2 distances:
distSpAndTp - distance between sp and tp
distEpAndTp - distance between ep and tp
If the sum of these 2 distances = distance between sp and ep, then tp is in range, otherwise it is out of range.

The best approach would be to first create a rectangle Rect (of android.graphics package), with x and width being the beginning and end of line, and y and height being the beginning and end of screen height.
Then use the Rect method Rect.contains(int x, int y) to check if the point coordinates lie within.
For floats, use RectF class instead.

This approach involves using 2D vectors (which you should have been using anyway, makes working in any coordinate system a lot easier) and the dot (scalar) product. It does not require any relatively expensive operations like the square root or trignometic functions, and therefore is very performant.
Let A and B be the start and end points (by point I mean a vector representing a position in 2D space) of the line segment, in any order. If P is the point to test, then:
If dot(PA, AB) and dot(PB, AB) have the same sign, the point lies outside the region (like p1 in your example).
If the dot products above have opposite signs, the point lies inside the region (like p2).
Where PA = A - P, PB = B - P and AB = B - A.
This condition can be surmised as follows:
if dot(PA, AB) * dot(PB, AB) <= 0 {
// Opposite signs, inside region
// If the product is equal to zero, the point is on one of the dotted lines
}
else {
// Same signs, outside region
}

Let's say, x1 is the beginning of the line and x2 is the end. Then ax is the dot in an horizontal plan and; y1, y2 and ay in vertical plan.
if((ax >= x1 && ax <= x2) && (ay >= y1 && ay <= y2)){ // do your work
}

There are a few answers already but there is another solution that will give you the unit distance on the line segment that the points is perpendicular to.
Where then line is x1,y1 to x2,y2 and the point is px,py
Find the vector from line start to end
vx = x2 - x1;
vy = y2 - y1;
And the vector from the line start (or end) to the point
vpx = px - x1;
vpy = py - y1;
And then divide the dot product of the two vectors by the length squared of the line.
unitDist = (vx * vpx + vy * vpy) / (vx * vx + vy * vy);
If the perpendicular intercept is on the line segment then unitDist will be 0 <= unitDist <= 1
In shortened form
x2 -= x1;
y2 -= y1;
unitDist = (x2 * (px - x1) + y2 * (py - y1)) / (x2^2 + y2^2);
if (unitDist >= 0 && unitDist <= 1) {
// point px,py perpendicular to line segment x1,y1,x2,y2
}
You also get the benefit of being able to get the point on the line where the intercept is.
p2x = vx * unitDist + x1;
p2y = vy * unitDist + y1;
And thus the distance that the point is from the line (note not line segment but line)
dist = hypot(p2x - px, p2y - py);
Which is handy if you are using a point to select from many lines by using the minimum distance to determine the selected line.

This can be solved nicely using complex numbers.
Let a and b the endpoints of the segment. We use the transformation that maps the origin 0 to a and the point 1 to b. This transformation is a similarity and its expresion is simply
p = (b - a) q + a
as you can verify by substituting q=0 or q=1. It maps the whole stripe perpendicular to the given segment to the stripe perpendicular to the segment 0-1.
Now the inverse transform is obviously
q = (p - a) / (b - a),
and the desired condition is
0 <= Re((p - a) / (b - a)) <= 1.
To avoid the division, you can rewrite
0 <= Re((p - a) (b - a)*) <= |b-a|²
or
0 <= (px - ax)(bx - ax) + (py - ay)(by - ay) <= (bx - ax)² + (by - ay)².

Related

Detect collision with lines and limit movement

I'm making a game with libGDX in Java. I'm trying to make a collision detection. As you can see in the image, I have a line which is a wall and a player with specified radius. The desired position is the next location which the player is trying to be in. But because there is a wall, he's placed in the Actual Position which is on the Velocity vector, but more closer to the prev location. I'm trying to figure out how can I detect that closer position?
My attempt:
private void move(float deltaTime) {
float step;
beginMovementAltitude();
if (playerComponent.isWalking())
step = handleAcceleration(playerComponent.getSpeed() + playerComponent.getAcceleration());
else step = handleDeacceleration(playerComponent.getSpeed(), playerComponent.getAcceleration());
playerComponent.setSpeed(step);
if (step == 0) return;
takeStep(deltaTime, step, 0);
}
private void takeStep(float deltaTime, float step, int rotate) {
Vector3 position = playerComponent.getCamera().position;
float x = position.x;
float y = position.y;
int radius = playerComponent.getRadius();
auxEnvelope.init(x, x + radius, y, y + radius);
List<Line> nearbyLines = lines.query(auxEnvelope);
float theta;
int numberOfIntersections = 0;
float angleToMove = 0;
Gdx.app.log(step + "", "");
for (Line line : nearbyLines) {
VertexElement src = line.getSrc();
VertexElement dst = line.getDst();
auxVector3.set(playerComponent.getCamera().direction);
auxVector3.rotate(Vector3.Z, rotate);
float nextX = x + (step * deltaTime) * (auxVector3.x);
float nextY = y + (step * deltaTime) * playerComponent.getCamera().direction.y;
float dis = Intersector.distanceLinePoint(src.getX(), src.getY(), dst.getX(), dst.getY(), nextX, nextY);
boolean bodyIntersection = dis <= 0.5f;
auxVector21.set(src.getX(), src.getY());
auxVector22.set(dst.getX(), dst.getY());
auxVector23.set(nextX, nextY);
if (bodyIntersection) {
numberOfIntersections++;
if (numberOfIntersections > 1) {
return;
}
theta = auxVector22.sub(auxVector21).nor().angle();
float angle = (float) (180.0 / MathUtils.PI * MathUtils.atan2(auxVector23.y - position.y, auxVector23.x - position.x));
if (angle < 0) angle += 360;
float diff = (theta > angle) ? theta - angle : angle - theta;
if (step < 0) step *=-1;
angleToMove = (diff > 90) ? theta + 180 : theta;
}
}
if (numberOfIntersections == 0) {
moveCameraByWalking(deltaTime, step, rotate);
} else {
moveCameraInDirection(deltaTime, step, angleToMove);
}
}
The idea is to find intersection of path of object center and the line moved by radius of the circle, see that picture.
At first, you need to find a normal to the line. How to do it, depends on how the line is defined, if it's defined by two points, the formula is
nx = ay - by
ny = bx - ax
If the line is defined by canonical equation, then coefficients at x and y define normal, if I remembered correctly.
When normal is found, we need to normalize it - set length to 1 by dividing coordinates by vector length. Let it be n.
Then, we will project starting point, desired point and randomly chosen point on line to n, treating them as radius vectors.
Projection of vector a to vector b is
project (a, b) = scalar_product (a, b) / length (b)**2 * b
but since b is n which length equals 1, we will not apply division, and also we want to only find length of the result, we do not multiply by b. So we only compute scalar product with n for each of three aforementioned points, getting three numbers, let s be the result for starting point, d for desired point, l for chosen point on the line.
Then we should modify l by radius of the circle:
if (s < d) l -= r;
else if (s > d) l += r;
If s = d, your object moves in parallel along the line, so line can't obstruct its movement. It's highly improbable case but should be dealt with.
Also, that's important, if l was initially between s and d but after modifying is no longer between then, it's a special case you may want to handle (restrict object movement for example)
Ather that, you should compute (d - s) / (l - s).
If the result is greater or equals 1, the object will not reach the line.
If the result is between 0 and 1, the line obstructs movement and the result indicates part of the path the object will complete. 0.5 means that object will stop halfway.
If the result is negative, it means the line is behind the object and will not obstruct movement.
Note that when using floating point numbers the result will not be perfectly precise, that's why we handle that special case. If you want to prevent this from happening at all, organize loop and try approximations until needed precision is reached.

How to determine if two points do not have any obstructions between them

I am currently trying to put together an algorithm where I can know if there is an obstruction between two defined points in a plane.
Here is an example image.
We can see with the image that point 1, 2, 3, & 6 are all accessible from the origin point. Points 4 and 5 are not. You pass through the polygon.
The code I am using is the following. pStartPoint and pEndPoint is the line from the origin to the point in question. The function checks all edges to see if the line passes through the edge.
public double GetSlopeOfLine(Point a, Point b){
double x = b.y - a.y;
double y = b.x - a.x;
return (x / y);
}
public double GetOffsetOfLine(double x, double y, double slope){
return (y - (slope * x));
}
public boolean IsPointAccessable(Point pStartPoint, Point pEndPoint){
//Define the equation of the line for these points. Once we have slope and offset the equation is
//y = slope * x + offset;
double slopeOfLine = GetSlopeOfLine(pStartPoint, pEndPoint);
double offSet = GetOffsetOfLine(pStartPoint.x, pStartPoint.y, slopeOfLine);
//Collision detection for each side of each obstacle. Once we get the point of collision, does it lie on the
//line in between the two points? If so, collision, and I can't reach that point yet.
for (Iterator<Obstacles> ObstacleIt = AdjustedObstaclesList.iterator(); ObstacleIt.hasNext();) {
Obstacles pObstacle = ObstacleIt.next();
int NumberOfEdges = pObstacle.getPoints().size();
for(int i=0; i<NumberOfEdges; i++){
//Get Edge[i];
int index = i;
Point pFirstPoint = (Point)pObstacle.getPoints().get(index);
if(i >= NumberOfEdges - 1)
index = 0;
else
index = i+1;
Point pNextPoint = (Point)pObstacle.getPoints().get(index);
double slopeOfEdge = GetSlopeOfLine(pFirstPoint, pNextPoint);
double offsetEdge = GetOffsetOfLine(pNextPoint.x, pNextPoint.y, slopeOfEdge);
int x = Math.round((float) ((-offSet + offsetEdge) / (slopeOfLine - slopeOfEdge)));
int y = Math.round((float) ((slopeOfLine * x) + offSet));
//If it lies on either point I could be looking at two adjacent points. I can still reach that point.
if(x > pStartPoint.x && x < pEndPoint.x && y > pStartPoint.y && y < pEndPoint.y &&
x > pFirstPoint.x && x < pNextPoint.x && y > pFirstPoint.y && y < pNextPoint.y){
return false;
}
}
}
return true;
}
If the line passes through and the point where the lines cross is found between pStartPoint and pEndPoint I am assuming that pEndPoint cannot be reached.
This function is not working and I am wondering if it has something to do with the fact that the origin is not at the bottom left but at the top left and that (width, height) of my window is located in the bottom right. Therefore the coordinate plane is messed up.
My mind must be mush because I cannot think how to adjust for this and if that is truly my mistake as I cannot seem to fix the error. I thought adjusting the slope and offset by multiplying each by -1 might have been the solution but that doesn't seem to work.
Is my solution the right one? Does my code seem correct in checking for an intersect point? Is there a better solution to see if a point is accessible.
There is also going to be the next step after this where once I determine what points are accessible if I am now on one of the points of the polygon. For example, from point 1 what points are accessible without crossing into the polygon?
First, I would like to say that using slopes for this kind of task is do-able, but also difficult due to the fact that they are very volatile in the sense that they can go from negative infinity to infinity with a very small change in the point. Here's a slightly different algorithm, which relies on angles rather than slopes. Another advantage of using this is that the coordinate systems don't really matter here. It goes like this (I reused as much of your existing code as I could):
public boolean IsPointAccessable(Point pStartPoint, Point pEndPoint) {
//Collision detection for each side of each obstacle. Once we get the point of collision, does it lie on the
//line in between the two points? If so, collision, and I can't reach that point yet.
for (Iterator<Obstacles> ObstacleIt = AdjustedObstaclesList.iterator(); ObstacleIt.hasNext();) {
Obstacles pObstacle = ObstacleIt.next();
int NumberOfEdges = pObstacle.getPoints().size();
for(int i=0; i<NumberOfEdges; i++){
//Get Edge[i];
int index = i;
Point pFirstPoint = (Point)pObstacle.getPoints().get(index);
if(i >= NumberOfEdges - 1)
index = 0;
else
index = i+1;
Point pNextPoint = (Point)pObstacle.getPoints().get(index);
// Here is where we get a bunch of angles that encode in them important info on
// the problem we are trying to solve.
double angleWithStart = getAngle(pNextPoint, pFirstPoint, pStartPoint);
double angleWithEnd = getAngle(pNextPoint, pFirstPoint, pEndPoint);
double angleWithFirst = getAngle(pStartPoint, pEndPoint, pFirstPoint);
double angleWithNext = getAngle(pStartPoint, pEndPoint, pNextPoint);
// We have accumulated all the necessary angles, now we must decide what they mean.
// If the 'start' and 'end' angles are different signs, then the first and next points
// between them. However, for a point to be inaccessible, it also must be the case that
// the 'first' and 'next' angles are opposite sides, as then the start and end points
// Are between them so a blocking occurs. We check for that here using a creative approach
// This is a creative way of checking if two numbers are different signs.
if (angleWithStart * angleWithEnd <= 0 && angleWithFirst * angleWithNext <= 0) {
return false;
}
}
}
return true;
}
Now, all that is left to do is find a method that calculates the signed angle formed by three points. A quick google search yielded this method (from this SO question):
private double getAngle(Point previous, Point center, Point next) {
return Math.toDegrees(Math.atan2(center.x - next.x, center.y - next.y)-
Math.atan2(previous.x- center.x,previous.y- center.y));
}
Now, this method should work in theory (I am testing to be sure and will edit my answer if I find any issues with signs of angles or something like that). I hope you get the idea and that my comments explain the code well enough, but please leave a comment/question if you want me to elaborate further. If you don't understand the algorithm itself, I recommend getting a piece of paper out and following the algorithm to see what exactly is going on. Hope this helps!
EDIT: To hopefully aid in better understanding the solution using angles, I drew a picture with the four base cases of how the start, end, first, and next could be oriented, and have attached it to this question. Sorry for the sloppiness, I drew it rather quickly, but this should in theory make the idea clearer.
If you have a low segment count (for instance, your example only shows 12 segments for three shapes, two shapes of which we know we can ignore (because of bounding box checks), then I would recommend simply performing line/line intersection checking.
Point s = your selected point;
ArrayList<Point> points = polygon.getPoints();
ArrayList<Edge> edges = polygon.getEdges();
for(Point p: points) {
Line l = new Line(s, p);
for(Edge e: edges) {
Point i = e.intersects(l);
if (i != null) {
System.out.println("collision", i.toString());
}
}
}
With an intersects method that is pretty straight forward:
Point intersects(Line l) {
// boring variable aliassing:
double x1 = this.p1.x,
y1 = this.p1.y,
x2 = this.p2.x,
y2 = this.p2.y,
x3 = l.p1.x,
y2 = l.p1.y,
x3 = l.p2.x,
y2 = l.p2.y,
// actual line intersection algebra:
nx = (x1 * y2 - y1 * x2) * (x3 - x4) -
(x1 - x2) * (x3 * y4 - y3 * x4),
ny = (x1 * y2 - y1 * x2) * (y3 - y4) -
(y1 - y2) * (x3 * y4 - y3 * x4),
d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (d == 0) return null;
return new Point(nx/d, ny/d);
}

Easiest way to check integer is either +1 or -1 Java

I want to the difference between two integers is +1 or -1. I think my code below is very clumsy to write. Is there any shorter way to check if two integers are just 1 apart? This seems like a simple solution, but I have 2d array of coordinates I want to check if two coordinates in the direct vicinity (either north, east, west, or south) of each other are selected.
Yes they are standard coordinates as the top left corner is 0,0, and the bottom right is 7,7. Essentially if one coordinate is selected, I wanted to check if there exists another coordinate where x or y differs by (+-) one.
//Since it's a 2d array, I am doing a nested loop. But comparison is below
int x1 = range(0,8); //all ints are range from 0 to 7
int y1 = range(0,8); //represent the current indices from the loop
int x2 = ...; //x2 represents the x index value of the previous loop
int y2 = ...; //y2 represents the y index value of the previous loop
if(x1+1 == x2){
Found an existing X coord just larger by one
}else if (x1-1 == x2){
Found an existing X coord smaller, and differ by one
}else if(y1+1 == y2){
Found an existing Y coord just 1 larger
}else if(y-1 == y2){
Found an existing Y coord just 1 smaller
}
Since we don't care whether the difference between x1 and x2 is 1 or -1, we can use the absolute value:
if (Math.abs(x1 - x2) == 1){
// x coordinates differ by 1
} else if (Math.abs(y1 - y2) == 1){
// y coordinates differ by 1
}
This works because if x1 is less than x2, then Math.abs(x1 - x2) = Math.abs(-1) = 1.
The simplest way I can think of is:
boolean differenceOfOne = Math.abs(n1 - n2) == 1;
Where n1 and n2 are numbers.
How about:
Math.abs(difference)==1
You can use Math.abs to evaluate the difference:
boolean isDifferenceOne = Math.abs(x1 - x2) == 1 && Math.abs(y1 - y2) == 1

Check if point is on line in Java Swing

I have drawn a line and then a point, and then I want to check if the point is on the line or not. I have taken a line coordinate in array (as there was more than one line). I want to check the current point in on the last line or not?
if (positionX1 == positionX2 && positionY1 == positionY2) {
float m = line.getSlope(
drawLines[currentLines - 1][2], drawLines[currentLines - 1][3],
drawLines[currentLines - 1][0], drawLines[currentLines - 1][1]);
m = Float.parseFloat(df.format(m));
float c = line.getIntercept(
drawLines[currentLines - 1][2], drawLines[currentLines - 1][3],
drawLines[currentLines - 1][0], drawLines[currentLines - 1][1]);
c = Math.round(c);
m1 = line.getSlope(positionX2, positionY2,
drawLines[currentLines - 1][0], drawLines[currentLines - 1][1]);
m1 = Float.parseFloat(df.format(m1));
System.out.println(m + " " + m1);
c1 = line.getIntercept(positionX2, positionY2,
drawLines[currentLines - 1][0], drawLines[currentLines - 1][1]);
c1 = Math.round(c1);
if (m == m1 && ((c == c1) || (c == c1 - 1) || (c == c1 + 1))) {
System.out.println("Point is on Line");
}
}
Problem is when a point is near the starting point of line or when a line is about vertical values of m1 and c1 changes with big difference. So, there's a problem for detecting if a point on line or not. How can I check for this situation?
Line2D.ptSegDist(x1, y1, x2, y2, xP, yP) returns 0.0 if the point (xP, yP) is on the line segment from (x1, y1) to (x2, y2). Line2D.ptLineDist does the same thing for the infinite line.
Use the vector form of the distance from a point to a line where the line is x = a + t n.
If instead of a unit vector n you use a non-unit vector N, then d = ||(a - p) - ((a - p) · N) N / ( N · N) ||, which eliminates a square root.
Assuming that the arrays of floats you are using to describe lines are interpreted as { x1, y1, x2, y2 }, then a = ( x1, y1 ) and N = ( x2 - x1, y2 - y1 ).
If the calculated distance is comparable to the measurement or arithmetic errors, the point is on the line. Again, you don't need to calculate the square root in the modulus but can compare the squared value.
In terms of an algorithm, a line (other than one which is vertical which has equation like x = constant) has a form y = mx + b. If your point satisfies that equation, then it is on the line. So all you need to is find the slope value of the line, and its y-intercept and check to see if the point's x and y values satisfy the equation for each line.
EDIT:
As is pointed out in an above comment, you could use the point-slope form (with slope being (y2-y1)/(x2/x1)) instead of the slope-intercept form. This would give you an equation that depends solely on y,x and the start and end points of the lines which would be much easier to code out (since you define a line by its start and end points, at least in swing). The only reason I suggested the slope-intercept form was because you were already attempting to use it in your algorithm.

Java 2D - Drag Mouse to rotate Image Smoothly

What is the logic that goes behind rotating an image via mouse movement. I know how to rotate using graphics2d.rotate...but having difficulty doing it with the mouse as the source for rotation. Here is basic steps:
get mouse x(dx) and mouse y(dy) distances from anchoring point( in this case that would be
the center of the image we want to rotate).
use this point in Math.arcTan2(dy,dx) to obtain the angle or rotation.
use the value from step to for Graphics2D.rotate method.
With that strategy, everytime i rotate the image, the image starts rotating from -pi and after 90 degrees of rotation it go goes back to -pi. I don't understand what I'm doing wrong here, it should be pretty basic.
Here is a part of the code :
// mouse dragged events get sent here.
public void mouseDragged( MouseEvent e ) {
int mx = e.getX( ), my = e.getY( );
// just checking if it falls within bounds of the image we
// want to rotate.
if( mx > speedKX || mx < speedKX + speedK.getWidth( ) || my > speedKY || my < speedKY + speedK.getHeight( )/2 )
{
theta += getTheta( e.getX( ), e.getY( ) );
}
}
As I understand you should look for the initial angle (when you clicked, the line between the anchor and your click) and the current angle (when you are dragging, same line). That angle (independent from the current distance to anchor point) will give you the rotation.
So you have to:
rotate(anglenow - angle0)
How to find it:
In both cases (initial click and mouse move event) you have to find angle between anchor and mouse point thinking the anchor as the origin.
I would use a method (getAngle(x1,y1,x2,y2). That method (except for race conditions like same x or same y, easily detectable) should calculate arctan(dy/dx).
Sign
But when you are dividing dy/dx it can be:
+ / + -> +
+ / - -> -
- / + -> -
- / - -> +
It is, four posibilities give you two kind of results. So, you have to look some condition to detect them.
I should review arctan doc or source to see what values it gives (between 0 and pi, or -pi/2 and +pi/2) and check then sign of the dx or the dy (depending on what range arctan returns) and use it to add/decrement pi to then resulting angle.
Then you'll get a getAngle method that return correctly the 360º space.
Edit
Javadoc says:
Math.atan retuns the arc tangent of an angle, in the range of -pi/2 through pi/2.
So, assuming your angle of value 0 is for the X axis as I assumed, the range it returns is the right hemisphere. So you have to distiguish the right hemisphere from the left one.
If you calculate dx = xtarget - xorigin (as you did for the division) it will be positive if the correct hemisphere is the right one, and negative if it's not.
So if dy < 0 then you have to add pi to your resulting angle. It will be between -pi/2 and 3pi/2. You also can correct the result by passing all to (-pi,pi) range or (0,2pi) range.
Edit: pseudocode, please double check!
onmousedown {
startpoint = (x,y);
startangle = getAngle(origin, startpoint);
}
onmousemove {
currentpoint = (x,y);
currentangle = getAngle(origin, currentpoint);
originalimage.rotate(currentangle - startangle);
}
getAngle(origin, other) {
dy = other.y - origin.y;
dx = other.x - origin.x;
if (dx == 0) // special case
angle = dy >= 0? PI/2: -PI/2;
else
{
angle = Math.atan(dy/dx);
if (dx < 0) // hemisphere correction
angle += PI;
}
// all between 0 and 2PI
if (angle < 0) // between -PI/2 and 0
angle += 2*PI;
return angle;
}

Categories

Resources