Here is the circle class:
public class Circle {
private double radius;
private double x;
private double y;
}
How can I tell if two objects from this class (circles) are colliding?
P.S. Can you use the method that avoids taking a square root?
double xDif = x1 - x2;
double yDif = y1 - y2;
double distanceSquared = xDif * xDif + yDif * yDif;
boolean collision = distanceSquared < (radius1 + radius2) * (radius1 + radius2);
dx = x2 - x1;
dy = y2 - y1;
radiusSum = radius1 + radius2;
return dx * dx + dy * dy <= radiusSum * radiusSum; // true if collision
The link from #instanceofTom in the comments is better... with pictures.
The circles will touch when the distance between their centres is equal to the sum of their radii, or collide when the distance is less.
Since we are using absolute distance, it is Ok to compare the square of the distance between centres with the square of the sum of the radii.
Here's the updated Java solution:
public boolean hasCollision(Circle circle){
double xDiff = x - circle.getX();
double yDiff = y - circle.getY;
double distance = Math.sqrt((Math.pow(xDiff, 2) + Math.pow(yDiff, 2)));
return distance < (radius + circle.getRadius());
}
Related
I want to generate some randoms polygon but I want it to be more or less centered in the middle of the given window coordinates.
Here is my code, it generates a random polygon but most of the time it's on the bottom of the window and I'd like to have it a bit more centered:
private static final double CORNER_MARGIN = 100.0; // max offset for a corner of the field, to randomize the polygon
private static double[] standardPolygon(double x1, double x2, double y1, double y2) {
// minX maxX minY maxY --> it's the coordinate of the window
double centerX = (x1 + x2) / 2;
double centerY = (y1 + y2) / 2;
// this is a standard polygon "centered" in the middle of the program window
return new double[]{
x1 - (x2 - x1) * RANDOM.nextDouble(), y2 + (y2 - y1) *RANDOM.nextDouble() * CORNER_MARGIN,
x2 + (x2 - x1) * RANDOM.nextDouble(), y2 + (y2 - y1) *RANDOM.nextDouble() * CORNER_MARGIN,
x2 + (x2 - x1) * RANDOM.nextDouble(), y1 - (y2 - y1) *RANDOM.nextDouble() * CORNER_MARGIN,
x1 - (x2 - x1) * RANDOM.nextDouble(), y1 - (y2 - y1) *RANDOM.nextDouble() * CORNER_MARGIN,
};
/*return new double[]{
x1 - RANDOM.nextDouble() * CORNER_MARGIN, y2 + RANDOM.nextDouble() * CORNER_MARGIN, // up left
x2 + RANDOM.nextDouble() * CORNER_MARGIN, y2 + RANDOM.nextDouble() * CORNER_MARGIN, // up right
x2 + RANDOM.nextDouble() * CORNER_MARGIN, y1 - RANDOM.nextDouble() * CORNER_MARGIN, // down right
x1 - RANDOM.nextDouble() * CORNER_MARGIN, y1 - RANDOM.nextDouble() * CORNER_MARGIN, // down left
};*/
}
The code in comment is working but now I tried to center it but I only get some rectangles/squares. How can I manage to keep random polygon forms but a bit more centered ?
[EDIT]
Here is how I draw the area of the polygon :
private void drawZone(Group group, IGameParameters gameParameters) {
Polygon polygon = new Polygon();
double[] points = gameParameters.dronePadDeliveryZonePolygon();
List<Double> pointsList = new ArrayList<>();
for (double point : points) pointsList.add(point);
polygon.getPoints().addAll(pointsList);
polygon.setFill(Color.ANTIQUEWHITE);
group.getChildren().add(polygon);
}```
You calculated the center but don't use it anywhere. Just so I understand correctly, this is a 4-sided polygon only and the corners randomly positioned at most 100 from the corner of the window?
I'm not 100% sure on how you want the polygon to be shaped but give this a try. Logically it works in my head, but I don't have a way to test the code right now.
private static final double CORNER_MARGIN = 100.0;
private static double[] standardPolygon(double x1, double x2, double y1, double y2) {
double centerX = (x1 + x2) / 2;
double centerY = (y1 + y2) / 2;
// Get the corner offsets
ox1 = x1 + CORNER_MARGIN * RANDOM.nextDouble(); // top left
oy1 = y1 + CORNER_MARGIN * RANDOM.nextDouble();
ox2 = x2 - CORNER_MARGIN * RANDOM.nextDouble(); // top right
oy2 = y1 + CORNER_MARGIN * RANDOM.nextDouble();
ox3 = x1 + CORNER_MARGIN * RANDOM.nextDouble(); // bottom left
oy3 = y2 - CORNER_MARGIN * RANDOM.nextDouble();
ox4 = x2 - CORNER_MARGIN * RANDOM.nextDouble(); // bottom right
oy4 = y2 - CORNER_MARGIN * RANDOM.nextDouble();
// Calculate the center of the polygon
double cx = (ox2 - ox1) / 2;
double cy = (oy2 - oy1) / 2;
// difference between window's center and polygon
double offsetX = centerX - cx;
double offsetY = centerY - cy;
// offset the calculated points so the polygon's center matches the window
ox1 += offsetX;
oy1 += offsetY;
ox2 += offsetX;
oy2 += offsetY;
ox3 += offsetX;
oy3 += offsetY;
ox4 += offsetX;
oy4 += offsetY;
// this is a standard polygon "centered" in the middle of the program window
return new double[]{
ox1, oy1,
ox2, oy2,
ox3, oy3,
ox4, oy4
};
}
The following code is called every 50ms.
// Start point
private double x;
private double y;
private double z;
private double y1;
#Override
public void run() {
double x1 = Math.cos(y1);
double z1 = Math.sin(y1);
double y2 = 4D - y1;
double x2 = Math.sin(y2);
double z2 = Math.cos(y2);
// First new point
double pX1 = x + x1;
double pY1 = y + y1;
double pZ1 = z + z1;
// Second new point
double pX2 = x + x2;
double pY2 = y + y2;
double pZ2 = z + z2;
if (y1 > 4D) {
y1 = 0D;
} else {
y1 = y1 + 0.1D;
}
}
Here is the output in a game. It generates two helices.
I cannot control more than the radius.
I am looking for code I can easily customize to fit my preferences.
How do I control the following aspects?
How fast the helix rises.
Where the helix begins.
helix is circular shape with 'linear' movement of the plane
you use plane xz as helix base and y axis as height
so you need:
r - radius
d - distance between two screws (the y movement after full circle)
t - parameter <0,1> determining the position on helix
h0,h1 - start end height of helix (y-axis)
a0 - angular start position [rad]
Now how to get the point on helix as function of parameter these parameters
aa=fabs(h1-h0)*2.0*M_PI/d; // angular speed coefficient
// if you need opposite angular direction then add aa=-aa;
x=r*cos(a0+aa*t);
z=r*sin(a0+aa*t);
y=h0+((h1-h0)*t);
aa can be precomputed once
now if t=0.0 then you get the start point of helix
if t=1.0 then you got the endpoint of helix
so speed is just how much you add to t during animation per timer cycle
d controls number of screw loops
h1-h0 is the helix height
code is in C++ (sorry I am not a JAVA coder)
One part of the helix begins at:
(x, y, z) = (1.0, 0.0, 0.0)
And the other at:
(x, y, z) = (-0.8, 4.0, -0.7)
And the particle rises at a rate of 0.1 (from y1 = y1 + 0.1D).
So, to control how fast the particles rise, just change this value.
To control where the helix begins you need to change the angle. For example, add some value to the sines and cosines. Like this:
Math.cos(y1 + dy);
To make more rotations before restarting from the ground you can multiply the angle. Make it twice as fast:
Math.cos(2 * y1);
Helix is circular shape with progressive Y value.
// Start point
private double x;
private double y;
private double z;
private double degree;
private double rY;
#Override
public void run() {
// We use the same formula that is used to find a point of a circumference
double rX = Math.cos(degree);
double rZ = Math.sin(degree);
// New point
double pX = x + rX;
double pY = y + rY;
double pZ = z + rZ;
if (degree > 2D * Math.PI) {
degree = 0D;
} else {
degree = degree + 0.2D;
}
if (pY > 2D) {
pY = 0D;
} else {
pY = pY + 0.02D;
}
}
I have been on this for hours, attempting different methods looking at just about every question. Perhaps I have it completely wrong, but I feel that I have my math of it correct, but no matter what numbers I input, I get the same output. My code is off somewhere and I have to turn it in by midnight.
It is the all so fun: Find if a point is within a triangle code. (for beginners)
import java.util.Scanner;
public class PointsTriangle {
// checks if point entered is within the triangle
//given points of triangle are (0,0) (0,100) (200,0)
public static void main (String [] args) {
//obtain point (x,y) from user
System.out.print("Enter a point's x- and y-coordinates: ");
Scanner input = new Scanner(System.in);
double x = input.nextDouble();
double y = input.nextDouble();
//find area of triangle with given points
double ABC = ((0*(100-0 )+0*(0 -0)+200*(0-100))/2.0);
double PAB = ((x*(0 -100)+0*(100-y)+0 *(y- 0))/2.0);
double PBC = ((x*(100-0 )+0*(0 -y)+200*(y-100))/2.0);
double PAC = ((x*(0 -100)+0*(100-y)+200*(y- 0))/2.0);
boolean isInTriangle = PAB + PBC + PAC == ABC;
if (isInTriangle)
System.out.println("The point is in the triangle");
else
System.out.println("The point is not in the triangle");
}//end main
}//end PointsTriangle
You placed the wrong value order into your formula; therefore, the result is wrong. If the 3 vertices are as the following
A(x1, y1) B(x2, y2), C(x3, y3)
then the area is calculated as
double ABC = Math.abs (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2;
After that, you just replace each vertex with the input point, we will have the following triangles: PBC, APC, ABP.
Put everything together, we will have the correct one
int x1 = 0, y1 = 0;
int x2 = 0, y2 = 100;
int x3 = 200, y3 = 0;
// no need to divide by 2.0 here, since it is not necessary in the equation
double ABC = Math.abs (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));
double ABP = Math.abs (x1 * (y2 - y) + x2 * (y - y1) + x * (y1 - y2));
double APC = Math.abs (x1 * (y - y3) + x * (y3 - y1) + x3 * (y1 - y));
double PBC = Math.abs (x * (y2 - y3) + x2 * (y3 - y) + x3 * (y - y2));
boolean isInTriangle = ABP + APC + PBC == ABC;
If you draw a picture, you can see the point has to satisfy simple inequalities (below / above / to the right of certain lines). Whether "on the edge" is in or out I will leave up to you:
Y > 0 (above the X axis)
X > 0 (to the right of the Y axis)
X + 2* Y < 200 (below the hypotenuse)
Write an if statement around these three and you're done:
if( (y > 0) && (x > 0) && (x + 2*y < 200) )
System.out.println("The point is in the triangle");
else
System.out.println("The point is not in the triangle");
I'm trying to simulate an analog stick on a mobile platform.
I calculate a stick vector which based on the position of the finger and the radius of the stick returns a value from -1 to 1.
public void calcStickVector(float x, float y)
{
float cx = getCenterX();
float cy = getCenterY();
float distX = x - cx;
float distY = y - cy;
distX /= getRadius();
distY /= getRadius();
distX = JMath.clamp(-1.0f, 1.0f, distX);
distY = JMath.clamp(-1.0f, 1.0f, distY);
stickVector.x = distX;
stickVector.y = distY;
}
public RectF getInnerStickRect()
{
float r = getInnerRadius();
float cx = getCenterX() + (getRadius() * getStickVector().x);
float cy = getCenterY() + (getRadius() * getStickVector().y);
innerStickRect.left = cx - r;
innerStickRect.top = cy - r;
innerStickRect.right = cx + r;
innerStickRect.bottom = cy + r;
return innerStickRect;
}
It almost works, but visually the inner stick, when moved around seems to form a square rather than going around in a circle. Is there something wrong with my logic?
Thanks
As it is, you really are making a box with 1's as the corners. You need to normalize the vector(divide x and y by distance) instead of dividing by radius and clamping.
double dist = Math.sqrt(distX*distX) + (distY*distY));
distX /= dist;
distY /= dist;
I'm creating a Canvas object ( lines, vertices, triangle, ...) and I would like to apply to them a rotation around a point.
I can't use the rotate() method of Canvas because points are attached to GeoPoint on a Map, so if I use the rotate() method the all map is rotating ...
The problem is that Canvas needs Point(int,int) and applying a rotation creates double because of cos and sin functions. So when I apply the rotation to the all points, because of casting double to int, I have some graphical issue that happens...
So I'm looking for the best solution.
Here my rotation code :
public Point rotatePoint(Point pt, Point center)
{
this.angle = ((this.angle/180)*Math.PI);
double cosAngle = Math.cos(this.angle);
double sinAngle = Math.sin(this.angle);
pt.x = center.x + (int) ((pt.x-center.x)*cosAngle-(pt.y-center.y)*sinAngle);
pt.y = center.y + (int) ((pt.x-center.x)*sinAngle+(pt.y-center.y)*cosAngle);
return pt;
}
the code has a small bug when calculating pt.y. (pt.x is updated but is later on used). instead try the following:
public Point rotatePoint(Point pt, Point center)
{
this.angle = ((this.angle/180)*Math.PI);
double cosAngle = Math.cos(this.angle);
double sinAngle = Math.sin(this.angle);
double dx = (pt.x-center.x);
double dy = (pt.y-center.y);
pt.x = center.x + (int) (dx*cosAngle-dy*sinAngle);
pt.y = center.y + (int) (dx*sinAngle+dy*cosAngle);
return pt;
}
I also use the following variation:
public Point rotatePoint(Point pt, Point center, double angleDeg)
{
double angleRad = (angleDeg/180)*Math.PI);
double cosAngle = Math.cos(angleRad );
double sinAngle = Math.sin(angleRad );
double dx = (pt.x-center.x);
double dy = (pt.y-center.y);
pt.x = center.x + (int) (dx*cosAngle-dy*sinAngle);
pt.y = center.y + (int) (dx*sinAngle+dy*cosAngle);
return pt;
}
I believe your solution is quite good. A small improvement would be to add 0.5 to the coordinates before casting them to integer and that way you will have the rounding we are usually used to - everything above 0.5 will get rounded to 1 for instance. Other than that I don't think you can avoid doing rounding as you want to place a continuous space into discrete one(i.e. the plane to a canvas).
Try this:
public Point rotatePoint(Point pt, Point anchorPoint, double angleDeg) {
double angleRad = Math.toRadians(angleDeg);
double dx = (pt.x - anchorPoint.x); //x-cord. is transformed to origin
double dy = (pt.y - anchorPoint.y); //y-cord. is transformed to origin
double ptX = anchorPoint.x + (dx * Math.cos(angleRad) - dy * Math.sin(angleRad));
double ptY = anchorPoint.y + (dx * Math.sin(angleRad) + dy * Math.cos(angleRad));
return new Point((int) ptX, (int) ptY);
}