I have a float[] newCoords variable that has a size of 9. The first 3 entries represent one vertex, the next 3 represent the second vertex and the last 3 represent the last vertex.
I have some code that is supposed to rotate a triangle anywhere in space when I feed it the coordinates. It looks like this:
float s = (float) Math.sin(0.5);
float c = (float) Math.cos(0.5);
float[] centroid = getCentroid(newCoords);
newCoords[0] -= centroid[0];
newCoords[1] -= centroid[1];
newCoords[3] -= centroid[0];
newCoords[4] -= centroid[1];
newCoords[6] -= centroid[0];
newCoords[7] -= centroid[1];
newCoords[0] = (newCoords[0] * c) - (newCoords[1] * s);
newCoords[1] = (newCoords[0] * s) + (newCoords[1] * c);
newCoords[3] = (newCoords[3] * c) - (newCoords[4] * s);
newCoords[4] = (newCoords[3] * s) + (newCoords[4] * c);
newCoords[6] = (newCoords[6] * c) - (newCoords[7] * s);
newCoords[7] = (newCoords[6] * s) + (newCoords[7] * c);
newCoords[0] += centroid[0];
newCoords[1] += centroid[1];
newCoords[3] += centroid[0];
newCoords[4] += centroid[1];
newCoords[6] += centroid[0];
newCoords[7] += centroid[1];
The problem is, its not rotating it properly, the triangles are spinning and getting smaller and smaller until they disappear for some reason, can anyone see why this is happening?
EDIT: whoops, almost forgot, here is my getCentroid() method.
private float[] getCentroid(float[] p1) {
float[] newCoords = new float[] {(p1[0] + p1[3] + p1[6]) / 3.0f,
(p1[1] + p1[4] + p1[7]) / 3.0f, 0};
return newCoords;
}
I see two problems with your code. Both are fixed with a little change.
You try to apply a rotation operation, taking X and Y coordinates as input and having the new X and Y as output. For every vertex you rotate, you have two lines of code: the first computes the X, the second the Y coordinate. But when computing the Y coordinate, you use the already rotated X coordinate! That's wrong.
There is also a numerical problem. You reuse the old values again and again, resulting in a chain of rotation computations a value makes though, so the numerical errors sum up. Never rely on such computations to work as expected. Instead, you should work with the original values and increase the angle in each frame. This makes sure that each value only participated in a single rotation computation.
For fixing both problems, keep the original coordinates somewhere in your code, I call them coords, and rewrite the code such that you take that array as input (keep newCoords as the output). Increase the rotation angle in each frame to achieve a rotation animation.
This fixes both problems because you get rid of that chain and also you have different arrays for input and output in your rotation function.
Pseudo-code:
// initial:
angle = 0.0;
coords = (initial coordinates)
// per frame:
angle += 0.5;
newCoords = rotate(coords, angle);
draw(newCoords);
Also, please note that 0.5 is a large angle if you want to rotate by that angle frame by frame. The math functions expect angle in radians (not degrees), so you might want to use a lower value depending on what you want to visualize in particular.
You might wonder why I reuse the old angle in each frame, as according to the above mentioned problem 2., it should introduce numerical problems, since it's also a chain of computations. That's not a problem with the rotation angle, as a simple summation doesn't show such bad numerical errors you experience with applying rotations. Yet it has some problems, but they only show up at very long running times when the angle reaches some billions. The reason why such a summation in general is not that bad is because you're changing the variable in the same direction in each frame as well as a slightly off rotation angle isn't noticed very much by the user.
Related
I'm trying to do some basic trigonometry with Java and LibGDX on android.
I've spent a long time googling "How to find an angle in right triangles".
I still don't really understand :(
I want to give an Actor subclass a random direction to follow. So what is the angle - and what should I set xSpeed and ySpeed to, in order to move at the correct angle.
I started writing an app to help me see how it works.
There are two objects - An origin point and a touch point. User presses screen, touchPoint moves to where user touched. Methods fire to figure out the appropriate values. I know the XDistance and YDistance between the two points. That means I know the Opposite length and the Adjacent length. So all I need to do is tan-1 of (opposite / adjacent), am I right?
I just don't understand what to do with the numbers my program spits out.
Some code:
In create event of main class:
stage.addListener(new ClickListener() {
#Override
public void touchDragged(InputEvent event, float x, float y, int pointer) {
touchPoint.setX(x);
touchPoint.setY(y);
touchPoint.checkDistance(); // saves x and y distances from origin in private fields
atan2D = getAtan2(touchPoint.getYDistance(), touchPoint.getXDistance());
tanhD = getTanh(touchPoint.getYDistance(), touchPoint.getXDistance());
xDistanceLbl.setText("X Distance: " + touchPoint.getXDistance());
yDistanceLbl.setText("Y Distance: " + touchPoint.getYDistance());
atan2Lbl.setText("Atan2: " + atan2D);
tanhLbl.setText("Tanh: " + tanhD);
angleLbl.setText("Angle: No idea");
}
})
...
private double getAtan2(float adjacent, float opposite) {
return Math.atan2(adjacent, opposite);
}
private double getTanh(float adjacent, float opposite) {
return Math.tanh((adjacent / opposite));
}
These two functions give me numbers between (atan2: -pi to pi) and (tanh: -1.0 to 1.0)
How do I turn these values into angles from which I can then work backwards and get the opposite and adjacent again?
Doing this should allow me to create and object with a random direction, which I can use in 2D games.
atan2 gives you direction in radians. Direction from origin (0,0) to touchPoint. If you need direction from some object to touchPoint, then subtract object coordinates. Perhaps you also want to see direction in degrees (this is only for human eyes)
dx = x - o.x
dy = y - o.y
dir = atan2(dy, dx)
dir_in_degrees = 180 * dir / Pi
I you have direction and want to retrieve coordinate differences, you need to store distance
distance = sqrt(dx*dx + dy*dy)
later
dx = distance * cos(dir)
dy = distance * sin(dir)
But note that often storing dx and dy is better, because some calculations might be performed without trigonometric functions
Just noticed - using tanh is completely wrong, this is hyperbolic tangent function, it has no relation to geometry.
You can use arctan, but it gives angle in half-range only (compared with atan2)
I had written before about implementing a map in my libgdx project.
I did that using a snapshot of said google map, importing the GPS bounds of the snapshot, the route-latlong values, a locationservice (via interface) and the snapshot as Gdx.files.local string.
Hopefully, the last issue I have right now is that the route is rotated about 45 degrees clockwise. Otherwise my 'enemies' walk a perfect path. I already figured out that I had to 'flip' my y-axis; before that it was rotated AND flipped upside down.
I was hoping someone here with more experience might have dealt with something similar before and has some advice :)
This is basically the code that creates a Waypoint array, after converting the GPS coordinates to pixel-coordinates that correspond to the gps-bounds of the map-snapshot (bottom-left-corner and upper-right-corner see here, as well as the width and height of the map-texture.
private void convertPathToScreen(double[] gpsRoute){
for(int i = 0; i<gpsRoute.length; i++){
if(i % 2 != 0) {
screenRouteCoordinates[i] =
x_GpsToScreenConversion(gpsRouteCoordinates[i]);
}
else{
screenRouteCoordinates[i] =
y_GpsToScreenConversion(gpsRouteCoordinates[i]);
}
}
}
public int x_GpsToScreenConversion(double x_pointInGpsCoords){
double percentage = 1 - Math.abs((x_pointInGpsCoords - x_GpsMin) /
(x_GpsMax - x_GpsMin));
return (int)((percentage* Math.abs(mapWidth - mapOrigin)) + mapOrigin);
}
public int y_GpsToScreenConversion(double y_pointInGpsCoords){
double percentage = (y_pointInGpsCoords - y_GpsMin) / (y_GpsMax - y_GpsMin);
return (int)((percentage* Math.abs(mapHeight - mapOrigin)) + mapOrigin);
}
Edit: Now that I think of it, the error might be in my pathfinding code, although I tested it before moving my project forward and it worked solidly for all values I put in. Anyway, for completness...es sake
private void calculatePathing(){
angle = (float) (Math.atan2(waypointsToGoal[waypoint].y - getY(), waypointsToGoal[waypoint].x - getX()));
velocity.set((float) Math.cos(angle) * speed, (float) Math.sin(angle) * speed);
}
So the question is basically: How do I fix the 90° clockwise rotation that buggers up my game? Can I rotate the coordinates of the array around the center of the map (where all enemies walk to) or is there a mistake in the conversion-code here?
Solution: (Patchwork, but it gets the job done!)
I simply rotated my waypoints by the degree I needed around the destination-point. It doesn't solve the underlying issue, but it solves the symptom.
private void createWaypointArray(){
//formula requires radians
double angle = Math.toRadians(90);
double current_x;
double current_y;
// waypointCache.size()-1 gets me the last waypoint, the destination around which I rotate
double center_x = waypointCache.get(waypointCache.size()-1).x;
double center_y= waypointCache.get(waypointCache.size()-1).y;
// Loop through Vector2 Array, rotate the points around destination and save them
for(int i = 0; i < waypointCache.size()-1; i++){
current_x = waypointCache.get(i).x;
current_y = waypointCache.get(i).y;
waypointCache.get(i).x = (float)((current_x-center_x) * Math.cos(angle) - (current_y-center_y) * Math.sin(angle) + center_x);
waypointCache.get(i).y = (float)((current_x-center_x) * Math.sin(angle) + (current_y-center_y) * Math.cos(angle) + center_y);
// this does work, but also translates the points because it rotates around the
// worldaxis, usable when points lie on normal kartesian axis I guess
// waypointCache.get(i).rotate(90);
}
this.wayPointArray = waypointCache.toArray(new Vector2[waypointCache.size()]);
}
I've made a Java program that displays lines in 3d space projected onto the 2d view, and so far, it's been working pretty well. I tried to make it possible to essentially rotate the 'world' about the camera's position about any axis, but now I'm running into some problems.
public void rotate(){
float ax = main.angleX; //main = camera
float ay = main.angleY;
float az = main.angleZ;
for(Line3d line : lines){ //all lines in the world
Vector3d start = Vector3d.Vector3dPMinus(line.start, main.getPoint()); //vetor value of starting point of line - camera's position
Vector3d end = Vector3d.Vector3dPMinus(line.end, main.getPoint());
start.rotate(ax, ay, az);
end.rotate(ax, ay, az); //rotate each vector
line.start = Point3d.pointFromVector3d(start).add(main.getPoint());
line.end = Point3d.pointFromVector3d(end).add(main.getPoint()); //vectors back into points
}
}
Rotation function:
public Vector3d rotate(float ax, float ay, float az){
Math.toRadians(ax *= 90);
Math.toRadians(ay *= 90);
Math.toRadians(az *= 90);
y = (float) (y * Math.cos(ax) - z * Math.sin(ax));
z = (float) (y * Math.sin(ax) + z * Math.cos(ax));
x = (float) (x * Math.cos(ay) + z * Math.sin(ay));
z = (float) (z * Math.cos(ay) - x * Math.sin(ay));
x = (float) (x * Math.cos(az) - y * Math.sin(az));
y = (float) (x * Math.sin(az) + y * Math.cos(az));
return this;
}
I've set it rotate about the x axis 3 times per second, and it displays exactly what I want it to before it starts rotating, but once it starts rotating, there's just some unidentifiable mess of usually just one horizontal line.
Is the method I used for rotating not right? Is there a better way to do it?
A Rotation of a 3d vector around the 3 axis is not that trivial as one might think. The thing you are probably trying to do is rotating with so called Euler Angles. You should be familiar with matrices to work with 3d space. I checked your rotations and they should work fine. BUT you should keep the following in mind: When you are rotating around an angle. The following rotations are affected by the previous rotation. You are rotating the rotation axis too.
To avoid this behaivour one ugly possibility is to rotate around a free axis. And when you are rotating around the x axis first. You rotate the y axis in reverse and rotate then your point around this y'. When you are rotating around z you need to rotate z axis with your reversed x and y rotation and then rotate around this z'. When you are doing this, you can always rotate around your world coordinatesystem. You should really use some math Library to accomplish this. It makes your life much easier. When you want to code it yourself. You need a proper matrice class with multiplication of matrices and vectors and some inversion method.
Your approach appears to take a reasonable general form. It looks like you are rotating the line endpoints relative to the current camera position, which is correct, and the three specific rotations you are performing could also be correct (but see below).
However, the three Math.toRadians() calls cannot be doing anything useful, because you ignore their results. Moreover, the expression ax *= 90 and its mates look awfully suspicious: are ax, ay, and az really expressed as fractions of a quarter-circle? That seems doubtful, and if it were the case then you would want to multiply by Math.PI/2 and skip toRadians(). On the other hand, if they are expressed in degrees then the following version of rotate() is correct for one reasonable definition of ax, ay, and az, and some possible Vector3D implementations:
public Vector3d rotate(double ax, double ay, double az){
ax = Math.toRadians(ax);
ay = Math.toRadians(ay);
az = Math.toRadians(az);
y = (float) ( y * Math.cos(ax) - z * Math.sin(ax));
z = (float) ( y * Math.sin(ax) + z * Math.cos(ax));
x = (float) ( x * Math.cos(ay) + z * Math.sin(ay));
z = (float) (-x * Math.sin(ay) + z * Math.cos(ay));
x = (float) ( x * Math.cos(az) - y * Math.sin(az));
y = (float) ( x * Math.sin(az) + y * Math.cos(az));
return this;
}
Overall, though, I am also a bit dubious of the correctness of the ax, ay, and az for this purpose. In particular, be aware that you cannot just accumulate separate x, y, and z rotation increments independently, as the resulting aggregate rotation depends greatly on the order in which the incremental rotations are performed. Moreover, even if ax, ay, and az correctly describe the orientation of the camera, it is unlikely that applying the same rotation to the world is what you actually want to do.
DESPITE ALL THE FOREGOING, though, I don't see any reason why your code would distort the model as you describe it doing. I don't think it will apply the rotation you want (even with my suggested fix), but the reason for the distortion is likely somewhere else.
I'm meant to draw a pentagon with lines going from the vertices to the centre. These 'arms' are being drawn correctly but when I try to connect the vertices it is being drawn incorrectly. To connect the lines I placed another draw function in the loop as below, which should take the end point coordinates of the first line drawn as the starting point, and the end point coordinates of the next 'arm' that is drawn in the iteration, as its end point. Am I missing something here? Am I wrong the use 'i+angle' in the second draw?
for (int i = 0; i < arms; i += angle) {
double endPointX = armLength * Math.cos(i*angle-Math.PI/2);
double endPointY = armLength * Math.sin(i*angle-Math.PI/2);
double endPointX2 = armLength * Math.cos((i+angle)*angle-Math.PI/2);
double endPointY2 = armLength * Math.sin((i+angle)*angle-Math.PI/2);
g2d.drawLine(centreX, centreY,centreX+ (int) endPointX,centreY+ (int) endPointY);
g2d.drawLine(centreX+ (int) endPointX,centreY+ (int) endPointY, (int) endPointX2,(int) endPointY2);
}
I have a solution for this here in PolygonFactory
Abstractly, the way to generate a regular polygon with n points is to put these points on the unit circle. So:
Calculate your angle step, which is 2 * pi / #vertices
Calculate your radius
Starting at angle 0 (or an offset if you want) use Math.sin(angle) and Math.cos(angle) to calculate the x and y coordinates of your vertices
Store the vertex points somewhere / somehow. If you look at the Polygon class or the class I wrote, you can get some ideas on how to do this in a way that is friendly to converting to a java.awt.Polygon.
I'm trying to write a java mobile application (J2ME) and I got stuck with a problem: in my project there are moving circles called shots, and non moving circles called orbs. When a shot hits an orb, it should bounce off by classical physical laws. However I couldn't find any algorithm of this sort.
The movement of a shot is described by velocity on axis x and y (pixels/update). all the information about the circles is known: their location, radius and the speed (on axis x and y) of the shot.
Note: the orb does not start moving after the collision, it stays at its place. The collision is an elastic collision between the two while the orb remains static
here is the collision solution method in class Shot:
public void collision(Orb o)
{
//the orb's center point
Point oc=new Point(o.getTopLeft().x+o.getWidth()/2,o.getTopLeft().y+o.getWidth()/2);
//the shot's center point
Point sc=new Point(topLeft.x+width/2,topLeft.y+width/2);
//variables vx and vy are the shot's velocity on axis x and y
if(oc.x==sc.x)
{
vy=-vy;
return ;
}
if(oc.y==sc.y)
{
vx=-vx;
return ;
}
// o.getWidth() returns the orb's width, width is the shot's width
double angle=0; //here should be some sort of calculation of the shot's angle
setAngle(angle);
}
public void setAngle(double angle)
{
double v=Math.sqrt(vx*vx+vy*vy);
vx=Math.cos(Math.toRadians(angle))*v;
vy=-Math.sin(Math.toRadians(angle))*v;
}
thanks in advance for all helpers
At the point of collision, momentum, angular momentum and energy are preserved. Set m1, m2 the masses of the disks, p1=(p1x,p1y), p2=(p2x,p2y) the positions of the centers of the disks at collition time, u1, u2 the velocities before and v1,v2 the velocities after collision. Then the conservation laws demand that
0 = m1*(u1-v1)+m2*(u2-v2)
0 = m1*cross(p1,u1-v1)+m2*cross(p2,u2-v2)
0 = m1*dot(u1-v1,u1+v1)+m2*dot(u2-v2,u2+v2)
Eliminate u2-v2 using the first equation
0 = m1*cross(p1-p2,u1-v1)
0 = m1*dot(u1-v1,u1+v1-u2-v2)
The first tells us that (u1-v1) and thus (u2-v2) is a multiple of (p1-p2), the impulse exchange is in the normal or radial direction, no tangential interaction. Conservation of impulse and energy now leads to a interaction constant a so that
u1-v1 = m2*a*(p1-p2)
u2-v2 = m1*a*(p2-p1)
0 = dot(m2*a*(p1-p2), 2*u1-m2*a*(p1-p2)-2*u2+m1*a*(p2-p1))
resulting in a condition for the non-zero interaction term a
2 * dot(p1-p2, u1-u2) = (m1+m2) * dot(p1-p2,p1-p2) * a
which can now be solved using the fraction
b = dot(p1-p2, u1-u2) / dot(p1-p2, p1-p2)
as
a = 2/(m1+m2) * b
v1 = u1 - 2 * m2/(m1+m2) * b * (p1-p2)
v2 = u2 - 2 * m1/(m1+m2) * b * (p2-p1)
To get the second disk stationary, set u2=0 and its mass m2 to be very large or infinite, then the second formula says v2=u2=0 and the first
v1 = u1 - 2 * dot(p1-p2, u1) / dot(p1-p2, p1-p2) * (p1-p2)
that is, v1 is the reflection of u1 on the plane that has (p1-p2) as its normal. Note that the point of collision is characterized by norm(p1-p2)=r1+r2 or
dot(p1-p2, p1-p2) = (r1+r2)^2
so that the denominator is already known from collision detection.
Per your code, oc{x,y} contains the center of the fixed disk or orb, sc{x,y} the center and {vx,vy} the velocity of the moving disk.
Compute dc={sc.x-oc.x, sc.y-oc.y} and dist2=dc.x*dc.x+dc.y*dc.y
1.a Check that sqrt(dist2) is sufficiently close to sc.radius+oc.radius. Common lore says that comparing the squares is more efficient. Fine-tune the location of the intersection point if dist2 is too small.
Compute dot = dc.x*vx+dcy*vy and dot = dot/dist2
Update vx = vx - 2*dot*dc.x, vy = vy - 2*dot*dc.y
The special cases are contained inside these formulas, e.g., for dc.y==0, that is, oc.y==sc.y one gets dot=vx/dc.x, so that vx=-vx, vy=vy results.
Considering that one circle is static I would say that including energy and momentum is redundant. The system's momentum will be preserved as long as the moving ball contains the same speed before and after the collision. Thus the only thing you need to change is the angle at which the ball is moving.
I know there's a lot of opinions against using trigonometric functions if you can solve the issue using vector math. However, once you know the contact point between the two circles, the trigonometric way of dealing with the issue is this simple:
dx = -dx; //Reverse direction
dy = -dy;
double speed = Math.sqrt(dx*dx + dy*dy);
double currentAngle = Math.atan2(dy, dx);
//The angle between the ball's center and the orbs center
double reflectionAngle = Math.atan2(oc.y - sc.y, oc.x - sc.x);
//The outcome of this "static" collision is just a angular reflection with preserved speed
double newAngle = 2*reflectionAngle - currentAngle;
dx = speed * Math.cos(newAngle); //Setting new velocity
dy = speed * Math.sin(newAngle);
Using the orb's coordinates in the calculation is an approximation that gains accuracy the closer your shot is to the actual impact point in time when this method is executed. Thus you might want to do one of the following:
Replace the orb's coordinates by the actual point of impact (a tad more accurate)
Replace the shot's coordinates by the position it has exactly when the impact will/did occur. This is the best scenario in respect to the outcome angle, however may lead to slight positional displacements compared to a fully realistic scenario.