The following code rotates the line towards the mouse position using a simple ease function, but the problem is that the atan2() methods works form -PI to PI, making the line to rotate backwards when the angle reach either of the limits, I can make it to rotate from 0 to TWO_PI but there is no different as the line will rotate backwards until it reach the targetAngle, if I dont use the easing calculation works fine because there jump from -PI to PI is unnoticeable, so how can I ease my rotation and avoid this problem?
float angle = 0;
float targetAngle = 0;
float easing = 0.1;
void setup() {
size(320, 240);
}
void draw() {
background(200);
noFill();
stroke( 0 );
// get the angle from the center to the mouse position
angle = atan2( mouseY - height/2, mouseX - width/2 );
// check and adjust angle to go from 0 to TWO_PI
if ( angle < 0 ) angle = TWO_PI + angle;
// ease rotation
targetAngle += (angle - targetAngle) * easing;
pushMatrix();
translate( width/2, height/2 );
rotate( targetAngle );
line( 0, 0, 60, 0 );
popMatrix();
}
Thanks
Not sure if I understood the problem correctly... Do you mean that if the mouse position is slightly less than +PI, and targetAngle is slightly greater than -PI, then the line rotates away from the mouse? The thing is that even if both values are in the same range (-PI, PI), they still can be quite far away from each other. You must adjust angle to fit the PI-neighbourhood of the current targetAngle value.
// get the angle from the center to the mouse position
angle = atan2( mouseY - height/2, mouseX - width/2 );
// check and adjust angle to be closer to targetAngle
if ( angle < targetAngle - PI ) angle = angle + TWO_PI;
if ( angle > targetAngle + PI ) angle = angle - TWO_PI;
This will work if targetAngle is in the range (-TWO_PI, TWO_PI). It seems that it will work for you. If targetAngle can have any value very far away from the working range, then you can use something like this:
// get the angle from the center to the mouse position
angle = atan2( mouseY - height/2, mouseX - width/2 );
// calculate the shortest rotation direction
float dir = (angle - targetAngle) / TWO_PI;
dir = dir - Math.round(dir);
dir = dir * TWO_PI;
// ease rotation
targetAngle += dir * easing;
Related
I create a 2d game similar to a classic diepio. I created a system for positioning the player's barrel in a specific direction. The updated angle is sent to the server. When the player clicks, the server creates a missile. This only works correctly when the barrel is attached to the center of the player's body. When I want to move the barrel away from the center of the body, there is a problem. I don't know how to update the server-side position where the projectile spawns.
In the image below, the barrel rotates around the center of the player's body. I marked the missile's flight path with the red line.
On this image, the barrels also have a rotation axis in the player's center, but have been shifted to the side. The green line marked the route the missile should take. Unfortunately, I don't know how to do it correctly.
How to update the projectile's spawn point by a given distance (e.g. 10) from the basic distance (if the barrel was not moved) based on the player's angle of rotation and his position?
Projectile spawn method:
float angle = (float) ((player.getRotation() + 90) * Math.PI / 180f);
float forceX = (float) Math.cos(angle);
float forceY = (float) Math.sin(angle);
spawnProjectile(player.getPosition().x + (forceX * 3f), player.getPosition().y + (forceY * 3f));
If I understood your question correctly, you want to find the two points marked in orange in the following image:
Since you know the direction in which the missiles should fly (the red line), the distance from the center position (e.g. 10) and you know that there is a 90° angle between the movement vector of the missile (red line) and the connection line between the two starting positions of the missiles (marked as black line in the image) you can calculate the resulting positions like this:
float angle = (float) ((player.getRotation() + 90) * Math.PI / 180f);
float forceX = (float) Math.cos(angle);
float forceY = (float) Math.sin(angle);
// the center point (start of the red line in the image)
float centerX = player.getPosition().x + (forceX * 3f);
float centerY = player.getPosition().y + (forceY * 3f);
float offsetFromCenterDistanceFactor = 1f; // increase this value to increase the distance between the center of the player and the starting position of the missile
// the vector towards one of the starting positions
float offsetX1 = forceY * offsetFromCenterDistanceFactor;
float offsetY1 = -forceX * offsetFromCenterDistanceFactor;
// the vector towards the other starting position
float offsetX2 = -offsetX1;
float offsetY2 = -offsetY1;
//spawn the upper missile
spawnProjectile(centerX + offsetX1, centerY + offsetY1);
//spawn the lower missile
spawnProjectile(centerX + offsetX2, centerY + offsetY2);
For more detail on the calculation of the orthogonal vectors see this answer.
The following is a Processing sketch.
Dead centre coordinates are 0,0.
This means the far-left x coord is -250 and the far right x coord is 250. Similar dimension for y.
I want to move the mouse around the centre of the screen and have the relative coordinate appear on the radius, (i.e. mouse at coordinates 45,0 should mark point at 90,0).
The below code works but only for the right side of the screen, in short, angles up to 180. What is missing for this to work for the right hand side?
void draw(){
background(0);
fill(255);
stroke(255);
strokeWeight(5);
translate(width/2,height/2);
// mark center
point(0,0);
strokeWeight(12);
// mark mouse position (follow with point)
float x = mouseX - width/2;
float y = mouseY - height/2;
point(x,y);
// trace point on radius of circle same radius as width
float radius = width/2;
float sinAng = y/radius;
float cosAng = x/radius;
float m = sinAng/cosAng;
float angle = atan(m);
float boundaryX = cos(angle)*width/2;
float boundaryY = sin(angle)*height/2;
stroke(255,0,0);
point(boundaryX,boundaryY);
}
You're loosing the quadrant when calculating m...
-x/-y = x/y
Just correct the angle to the right quadrant by using the sign of x and y.
You can do this in fewer steps by using the atan2() function.
The atan2() function takes two parameters: the y distance between two points, and the x distance between two points, and it returns the angle between those points:
angle = atan2(y1-y0, x1-x0);
You can get rid of a few lines in your program by just doing this:
float x = mouseX - width/2;
float y = mouseY - height/2;
float angle = atan2(y, x);
float boundaryX = cos(angle)*width/2;
float boundaryY = sin(angle)*height/2;
No need to calculate the sinAng, cosAng, or m variables.
I'm trying to draw a circle on my canvas. Pseudocode of my algorithm looks like that
double R = 1.0;
// Draw 11 points, lying on the circle with the radius of 1
// and angle from 0 to 90 degrees
for(int i=0; i<=10; i++)
{
drawPoint( R*cos(PI*i/20), R*sin(PI*i/20) );
}
// Draw a circle with center at the (0; 0) and with the radius of 1
drawCircle(0, 0, R);
That's what I've got:
Looks fine, but there is one problem. When I increase radius only points with angles 0, 45 and 90 lie on a circle.
That's how it looks 72 degrees:
There is no any info about accuracy of the method drawCircle on developer.android.com.
I guess that it draws, based on the values at points with angles 0, 45, 90, ..., and calculate line in other positions very approximately.
I know, that I can draw circle as accurate as I want to, if I'll draw it like a polyline with tiny step, but it will work very slow.
So I want to find out - is there any methods to draw circle accurate in Android?
UPD 1:
How do I draw a points:
int x, y;
x = getPixelX(point.getX());
y = getPixelY(point.getY());
canvas.drawCircle(x, y, point.radius, paint);
Where getPixelX and getPixelY takes a coorditate of the point on plane and returns the same coordinate on the screen, basing on scale and offset.
I thought that I could make some mistake in those methods, but they work perfectly with the lines. I can zoom in lines and there is no error, all the points lies just on the line.
UPD 2:
There are comments, that probably I make a mistake in my calculations. I do not argue, perhaps you're right. So here is my "calculations".
How do I zoom in:
public void mouseWheelMoved(MouseWheelEvent e) {
// zoomQ is 0.9 or 1.1
double zoomQ = (e.getWheelRotation() + 10) / 10.0;
scaleX *= zoomQ;
scaleY *= zoomQ;
}
How do I move the plane:
public void mouseDragged(MouseEvent e) {
centerX -= (e.getX() - lastMouseX)/scaleX;
centerY -= (e.getY() - lastMouseY)/scaleY;
lastMouseX = e.getX();
lastMouseY = e.getY();
}
How do getPixelX/Y works:
public int getPixelX(double planeX) {
return (int)Math.round( scaleX*(planeX - centerX) + ScreenWidth/2 );
}
public int getPixelY(double planeY) {
return (int)Math.round( scaleY*(planeY - centerY) + ScreenHeight/2 );
}
What is the formula used to determining moving object's rotation angle from its velocity or vector direction of travel?
For example, if an airplane is moving toward position (x1,y1) = (200, 100) from position (x0, y0) = (0,0), which angle would the plane be facing?
By rotation angle you apparently mean azimuth. The function Math.atan2(dy, dx) is the right approach. In your example with p1 = (x1, y1) = (200,100) and p0 = (x0, y0) = (0,0), you'd want Math.atan2(y1 - y0, x1 - x0). This will return the angle in radians. To convert to degrees, multiply by 180 / Math.PI.
To get the angle between two points, you plug the points into this code:
var _radians:Number = Math.atan2(y2-y1, x2-x1);
"_radians" is the angle in radians.
To rotate a DisplayObject, you can use its rotation property, after converting the angle into degrees.
var _degrees:Number = _radians * ( 180 / Math.PI );
_displayObject.rotation = _degrees;
You may need to add a contant to the rotation to line up with your art.
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;
}