I tried to post a different topic for this but people didn't really seem to understand what I was trying to do, so, now I've closed that one and opened this one to give more detail and rephrase the question as a whole.
Ok.
So basically, I have an application which draws an Ellipse. Now, I have a certain number of points (that can be random) in which I have to rotate an image and draw at.
Using Maths I know that to get a point on an Ellipse based by using an angle I use the following equation;
final int radiusW = (width / 2);
final int radiusH = (height / 2);
final int angle = 120;
int pointX = (int) (radiusW + (radiusW * Math.cos(Math.toRadians(angle))));
int pointY = (int) (radiusH + (radiusH * Math.sin(Math.toRadians(angle))));
And that works fine, I can locate an absolute point around the perimeter of the Ellipse.
However, now I'm trying to draw an image on this point so that the image is rotated facing the center of ellipse and is centered on the point.
So, to get the image rotated to the center of the point I do the following;
final AffineTransform at = new AffineTransform();
at.rotate(Math.toRadians(angle - 90), image.getWidth() / 2, image.getHeight() / 2);
final AffineTransformOp ato = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
And then I get my new rotated BufferedImage using;
BufferedImage rotated = ato.filter(image, null);
However, I can't seem to be able to get the central point of the image anymore.
If the angle was 0 so that the Image was the original direction then I would simply do;
graphics.drawImage(rotated, pointX - rotated.getWidth() / 2, pointY - rotated.getHeight() / 2, this);
However I'm not sure how to find the central point and draw it based upon that on a rotated image.
I know it involves using cos and sin to multiply the original pointX and pointY by the rotation matrix but everytime I try and work out a solution it always draws completely wrong.
Any help would be very much appreciated as I've spent the best part of a day trying to resolve this.
Thank you.
The thing is that if you just use sin and cos to rotate the corner of the image you will end up with the new rotated position of that corner - when actually what you want to find is the new width and height.
The center is width/2, height/2
Use this to calculate your new width and height:
Calculate Bounding box coordinates from a rotated rectangle
I have done this with OpenCV, and there the image have been rotated but the resulted image was having the same width and height as the initial on. The image was cropped if it was getting out of the initial dimentions and there were black pixels if no information (the rotated image has no pixels in that place).
If you think that rotated has more pixels than the initial image you can verify with size() or length(). Or you can play with the diagonals of the initial rectangle (image size): compute the projection of the diagonals and thake the greatest or what you think. But I am sure that it is similar to the OpenCV case.
I don't know if this can help you, but I hope so.
Your question is not entirely clear but it seems to me that you have a misunderstanding of the nature of the angle used to parametrise your ellipse. The angle as you have it is merely used to parametrise the form of an ellipse equation. It is not the same as the polar angle (except at particular angles). That is to say if you evaluate a point on your ellipse using an angle of (pi/4) radians (45 degrees), then measured the angle that the line from the ellipse centre to your point makes with the axis, it will not measure 45 degrees (except for the case where the ellipse is actually a circle).
That is to say that
int pointX = (int) (radiusW + (radiusW * Math.cos(Math.toRadians(angle))));
int pointY = (int) (radiusH + (radiusH * Math.sin(Math.toRadians(angle))));
is just a parametrisation of an ellipse and that angle is not a polar angle and treating this angle as a rotation angle will not give accurate results (except at integer multiples of (pi/2) radians)
It seems to me that you require the polar form of an ellipse relative to its centre in order for your code to make sense in the context of using this angle for rotation.
It is also possible that I have misunderstood your question though, in which case this answer will be downvoted on a grand scale and I will delete it.
Related
Firstly, I am trying to make a simple game in Java. I have a viewport that shows a tile map and I have a tank in the middle that moves by controlling the JScrollBars of the scrollpane in which the viewport resides in. So far everything has been going well, until I needed to rotate an image. Here is a picture of the game: Note: the tank body and tilemap are on seperate panels and do not share the same graphics.
Picture of non rotated tank body:
Essentially, I want to rotate a buffered image around its center (rotating in place) using arrow keys. I already have the code for the keys, and I also have a method to try and rotate the buffered image given a buffered image and angle in degrees (the angle is changed to radians in the method). This method will return a buffered image that is rotated correctly. Here is the code:
public static BufferedImage rotateImage(BufferedImage image, double angle) {
if(angle == 0)
return image;
else {
angle = Math.toRadians(angle);
double x = Math.abs(Math.cos(angle));
double y = Math.abs(Math.sin(angle));
int newWidth = (int) Math.floor(image.getWidth()*x + image.getHeight()*y);
int newHeight = (int) Math.floor(image.getHeight()*x + image.getWidth()*y);
BufferedImage rotated = new BufferedImage(newWidth, newHeight, image.getType());
Graphics2D tool = rotated.createGraphics();
AffineTransform transformer = new AffineTransform();
transformer.rotate(angle, image.getWidth()/2, image.getHeight()/2);
tool.drawImage(image, transformer, null);
tool.dispose();
return rotated;
}
}
However, as the title suggests, the image gets cut off at the top and left sides of the image when rotated as shown:
Picture of rotated tank body:
So I have looked at many different forums but I could not solve my problem. I could add whitespace around the image, but that interferes a lot with collision detection which I plan to do later on. I know that it has to do something with the original display being smaller than the display of the rotated image, and I have tried to translate accordingly in many ways. If I translate with this line of code specifically,
transformer.translate((newWidth - image.getWidth())/2, (newHeight - image.getHeight())/2);
Then the image (tank body) rotates without cutting, but bounces out of place as shown (I drew a rectangle to show where it was):
Picture of rotated tank with translation:
I also have tried negating the translations too but it only avails to funky movements.
So, I really have no clue how to solve this, and I have been spending too much time on this problem. I would really appreciate a helpful answer that directly edits my method if possible.
Answer
So here is the opening idea that I needed to realize to answer this problem.
The method to translate and rotate is meant so that the image is not cut off. However, it won't be around the center as intended as seen in the 3rd picture. But again, the method is not intended to recenter it. The painting code itself needs to account for this shift. I simply added variables to account for this:
xOffset = (newWidth - image.getWidth())/2;
yOffset = (newHeight - image.getHeight())/2
And simply subtracted these from where I was painting the tank's body.
Thanks to #camickr for the solution
When rotating a square sprite around the center point, the target image should be larger than the original image by a factor of the square root of 2 (approx. 1.41). For example, a sprite will not be clipped at a rotation angle of 45 °.
I hope this information helps you to solve your problem.
I have run into a problem making a first person camera on LWJGL 2. I am using the following code to rotate the camera (up down left and right) based on how the mouse moves. This is basically what every other tutorial has, however, its movement is flawed and ends up spiraling out of control.
float mouseDX = Mouse.getDX();
float mouseDY = Mouse.getDY();
rotation.x = mouseDX;
rotation.y = mouseDY;
glRotatef(rotation.y, 1, 0, 0);
glRotatef(rotation.x, 0, 1, 0);
Rotation is a Vector3f
I am aware that the rotation.y is rotating the x access and the x is rotating the y. I am not totally sure why but it doesn't work for me unless its this way. The problem may be related to this.
Here is a video I made showing what I mean:
https://www.youtube.com/watch?v=V6Iu5oQuWo4&feature=youtu.be
In the video I attempt to show that both the x and y rotation work fine separately, but when used together they don't work at all.
I know this is only a small section of my code, but it is the only part dealing with rotation so the problem must be there somewhere.
The flaw that stands out to me is the value by which you rotate.
Mouse.getDY returns the change in y pixels so if you move your mouse half way down the screen you will move typically 300 pixels (800x600).
Now you also have glRotatef which rotates by radians which compared are tiny compared to degrees.(360 degrees -> 6.28 radians)
Now take 300 hundred pixels, use it as the number of radians to rotate by and you get 17188.7 degrees of rotation.
And that's the cause of your spiralling (47 revs/few milliseconds)
What you will need to do if divide your dy and dx by a good couple of hundred.
And you can also still use degrees by using Math.toRadians in the glRotatef method
I have a Canvas on which I've drawn a circle / 360 degree arc. I have the arc start drawing from -90 (the top) rather than the right (0) as is default.
I want to place a rectangle at the top of the same canvas and to reduce the sweep of the arc so that the two do not intersect. I've attached an image to illustrate
So what I need to do is work out what angle is represented by half of the rectangle so that I can adjust where to start drawing my arc. The centre of the circle is at the centre of my Canvas:
[canvas.width /2, canvas.height /2]
I've read some resources like this question but they haven't helped to do much more than make me feel like I know nothing. I tried a few failing formulas ending with this
double adjustment = Math.atan2(rectangleY - circleY, rectangleX - circleX) - Math.atan2(rectangleY - circleY, (rectangleX + rectangleWidth) - circleX);
Can somebody tell me what is the right way to calculate this in Java? I'd also like to know how to find where the rectangle intersects if that's possible (I.e. the width of the shaded orange part on the image) although this is of lesser importance to me right now
Let W be the width of the rectangle, R be radius of the circle, and A be the angle you're looking for.
There's a right-angle triangle with angle A at the center, R as the hypotenuse and W/2 as the side opposite angle A, so
W/2R = sin(A)
so
A = Math.asin(0.5*W/R);
Of course you can't use asin(0.5W/R) when W > 2R
EDIT
To answer the second problem (finding the intersection)
Let H be the distance from the center of the circle to the rectangle. When the rectangle is wide enough that the circle intersects the lower side, there's a right angle triangle with A at the center, R as the hypotenuse, and H as the side adjacent to A
H/R = cos(A) and A = Math.acos(H/R). Calculate both angles and use the smaller one.
I'm developing a tube shooter-esque game in java that simulates 3D without actually using any 3D libraries. Right now I have a player-controlled ship that rotates around the center point of the screen, using (in this case, for moving right).
angle += 0.1;
x = Math.cos(angle) * radius + cX;
y = Math.sin(angle) * radius + cY;
Where angle is the placement in relation to the center point (ex. 270 is directly under the center), x and y are the current ship position, radius is the distance from the center, and cX and cY are the center point's location.
Right now revolving around the point works smoothly, but I'm not sure how to handle rotating the actual ship to always point towards the center. I've looked around a lot online but can't figure out how an individual Image (or if that doesn't work, an array of drawLines) can be rotated without affecting other objects on the screen.
Long story short, how would one go about rotating an individual Image to constantly point towards a remote x,y location?
What you need is the AffineTransform class which is basically a matrix class in java. Graphics2D has a draw image variant which accepts an AffineTransform instance:
boolean java.awt.Graphics2D.drawImage(Image img, AffineTransform xform, ImageObserver obs)
To create a transform, you can use 2D matrix operations:
AffineTransform trans = new AffineTransform();
trans.translate(x, y);
trans.rotate(theta);
trans.scale(scalex, scaley);
etc...
Mind that the order is important, probably you will want to scale first, rotate and then traslate the image to the corresponding location. It should do fine.
Java has uses some 3D power to draw as fast as it can, it is faster than a software renderer, but quite far from native opengl.
Ok I've been trying to rotate a Rectangle that sits on top of an image. I have a Scrollable class that displays the Image. I can draw Rectangles on top of the Image. My problem is trying to rotate the Rectangles when the Image is rotated. The Rectangle gets lost and placed in the wrong location.
I've already tried suing Graphics2D, AffineTransform, createTransformedShape() but no luck.
What I'm trying to do now is to rotate the Rectangle manually. I'm trying to get the Rectangle Point(x,y) using below formula:
double rectX = (Math.cos(Math.toRadians(90)) * (x - anchorX) - Math.sin(Math.toRadians(90)) * (y - anchorY)) + anchorY;
double rectY = (Math.sin(Math.toRadians(90)) * (x - anchorX) - Math.cos(Math.toRadians(90)) * (y - anchorY)) + anchorY;
How can I find the anchorX and anchorY values using Java? I've tried diving the Image height by 2 but doesn't work for all rotation angles. Do I have to get the JPanel width and height or something? Is there a formula that Java uses to find anchor points?
I'm not sure of the goal, but I see two possible alternative approaches:
Use an inverse transform, as shown here.
Render the upright image and rectangle(s) into a BufferedImage and rotate the composite image, as shown here.
If you're trying to make it like a a box rolling across the top, you have to find the bottom corner in direction of travel. If you're rolling to the right, you need the bottom right corner.