How to get coordinates of drawed circle Java2D - java

Let's say I want a sprite to be circulating around certain point. I could draw a circle around this point using drawOval method but how to get specific coordinates of this oval on which moving sprite could be drawn on.

To get all points on the circumference of an ellipse (or oval), you can use the following formula (posX and posY are coords of the center of the oval and width and height are the width and height of the oval respectively):
x = posX + cos(angle) * width * 0.5
y = posY + sin(angle) * height * 0.5
Where angle goes from 0 to 2 * PI radians.
You can increment angle by something like delta_time * speed where delta_time is the time it took to render the last frame (or rather, time since the last frame) in seconds and speed is the speed (in unit/second) at which you want the sprite to move.

Related

Java LibGDX relative value addition based on angle and position

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.

Drawing Spiral Using Java in Processing

I have a Java program written in Processing I made that draws a spiral in processing but I am not sure how some of the lines of code work. I wrote them based on a tutorial. I added comments in capital letters to the lines I do not understand. The comments in lowercase are lines that I do understand. If you understand how those lines work, please explain in very simple terms! Thank you so much.
void setup()
{
size(500,500);
frameRate(15);
}
void draw()
{
background(0); //fills background with black
noStroke(); //gets rid of stroke
int circlenumber = 999;// determines how many circles will be drawn
float radius = 5; //radius of each small circle
float area = (radius) * (radius) * PI; //area of each small circle
float total = 0; //total areas of circles already drawn
float offset = frameCount * 0.01; //HOW DOES IT WORK & WHAT DOES IT DO
for (int i = 1; i <= circlenumber; ++i) { // loops through all of the circles making up the pattern
float angle = i*19 + offset; //HOW DOES IT WORK & WHAT DOES IT DO
total += area; // adds up the areas of all the small circles that have already been drawn
float amplitude = sqrt( total / PI ); //amplitude of trigonometric spiral
float x = width/2 + cos(angle) * amplitude;//HOW DOES IT WORK & WHAT DOES IT DO
float hue = i;//determines circle color based on circle number
fill(hue, 44, 255);//fills circle with that color
ellipse(x, 1*i, radius*2, radius*2); //draws circle
}
}
Essentially what this is doing is doing a vertical cosine curve with a changing amplitude. Here is a link to a similar thing to what the program is doing. https://www.desmos.com/calculator/p9lwmvknkh
Here is an explanation of this different parts in order. I'm gonna reference some of the variables from the link I provided:
float offset = frameCount * 0.01
What this is doing is determining how quickly the cosine curve is animating. It is the "a" value from desmos. To have the program run, each ellipse must change its angle in the cosine function just a little bit each frame so that it moves. frameCount is a variable that stores the current amount of frames that the animation/sketch has run for, and it goes up every frame, similar to the a-value being animated.
for (int i = 1; i <= circlenumber; ++i) {
float angle = i*19 + offset;
This here is responsible for determining how far from the top the current ellipse should be, modified by a stretching factor. It's increasing each time so that each ellipse is slightly further along in the cosine curve. This is equivalent to the 5(y+a) from desmos. The y-value is the i as it is the dependent variable. That is the case because for each ellipse we need to determine how far it is from the top and then how far it is from the centre. The offset is the a-value because of the reasons discussed above.
float x = width/2 + cos(angle) * amplitude
This calculates how far the ellipse is from the centre of the screen (x-centre, y value is determined for each ellipse by which ellipse it is). The width/2 is simply moving all of the ellipses around the centre line. If you notice on Desmos, the center line is y-axis. Since in Processing, if something goes off screen (either below 0 or above width), we don't actually see it, the tutorial said to offset it so the whole thing shows. The cos(angle)*amplitude is essentially the whole function on Desmos. cos(angle) is the cosine part, while amplitude is the stuff before that. What this can be treated as is essentially just a scaled version of the dependent variable. On desmos, what I'm doing is sqrt(-y+4) while the tutorial essentially did sqrt(25*i). Every frame, the total (area) is reset to 0. Every time we draw a circle, we increase it by the pi * r^2 (area of circle). That is where the dependent variable (i) comes in. If you notice, they write float amplitude = sqrt( total / PI ); so the pi from the area is cancelled out.
One thing to keep in mind is that the circles aren't actually moving down, it's all an illusion. To demonstrate this, here is some modified code that will draw lines. If you track a circle along the line, you'll notice that it doesn't actually move down.
void setup()
{
size(500,500);
frameRate(15);
}
void draw()
{
background(0); //fills background with black
noStroke(); //gets rid of stroke
int circlenumber = 999;// determines how many circles will be drawn
float radius = 5; //radius of each small circle
float area = (radius) * (radius) * PI; //area of each small circle
float total = 0; //total areas of circles already drawn
float offset = frameCount * 0.01; //HOW DOES IT WORK & WHAT DOES IT DO
for (int i = 1; i <= circlenumber; ++i) { // loops through all of the circles making up the pattern
float angle = i*19 + offset; //HOW DOES IT WORK & WHAT DOES IT DO
total += area; // adds up the areas of all the small circles that have already been drawn
float amplitude = sqrt( total / PI ); //amplitude of trigonometric spiral
float x = width/2 + cos(angle) * amplitude;//HOW DOES IT WORK & WHAT DOES IT DO
float hue = i;//determines circle color based on circle number
fill(hue, 44, 255);//fills circle with that color
stroke(hue,44,255);
if(i%30 == 0)
line(0,i,width,i);
ellipse(x, i, radius*2, radius*2); //draws circle
}
}
Hopefully this helps clarify some of the issues with understanding.

JAVA draw regular polygon

I am looking for an algorithm to draw regular polygon like triangle, quadrangle, pentagon, hexagon etc.
I guess it`s basically dealing with the fact that all polygon points are located on the line of the circle.
What`s the algorithm to calculate those N points for Polygon object?
After drawing a regular polygon I need to draw another regular polygon based on the first one but rotated by K degrees.
Use sin and cos:
double theta = 2 * Math.PI / sides;
for (int i = 0; i < sides; ++i) {
double x = Math.cos(theta * i);
double y = Math.sin(theta * i);
// etc...
}
To rotate just add a constant offset to the angle, i.e. theta * i + offset.
The vertices of an N-vertex polygon are located at the angles
(2*Math.PI*K)/N
where K goes from 0 to N-1, inclusive. The vertical coordinate can be calculated as a sine of the angle times the radius of the circumcircle; the horizontal coordinate is calculated the same way, except you need to multiply the radius by the cosine of the angle.
In order to turn your polygon by X degrees, convert X to radians, and add the result to the angle in the formula, like this:
(2*Math.PI*K)/N + Xrad
Finally, since the origin of the screen is in one of the corners, only a portion of your polygon is going to be visible. To avoid this, add an offset equal to the position of the circumcircle's center to each coordinate that you calculate.
sin, cos, radius, 2*PI / number of sides and a loop

How does this code that draws a stoplight with red, yellow and green lights work?

I'm having a lot of trouble grasping the concept of this example in my text book. The idea is to draw a stoplight with red, yellow and green lights. I have a couple of questions. I'm having trouble figuring out what part of the code does what.
Am I right to assume cx and cy are to figure out the center of the page?
Are fx and fy to figure out the center of the frame?
I don't know what dy does and why it's divided by 4 and not 3 for 3 lights and the LAMP_RADIUS totally confuses me.
On all three add(createFilledCircle) for red, yellow and green I don't understand how their position is calculated inside the stoplight frame.
In the method createFilledCircle() I don't understand GOval circle = newGOval(x-r, y-r, 2 * r, 2 * r);. I don't understand what x-r and y-r does and how that relates to position.
import acm. graphics.*;
import acm. program.*;
import java.awt.*;
public class DrawStoplight extends GraphicsProgram {
public void run () {
double cx = getWidth() / 2;
double cy = getHeight() / 2;
double fx = cx - FRAME_WIDTH / 2;
double fy = cy- FRAME_HEIGHT / 2;
double dy = FRAME_HEIGHT / 4 + LAMP_RADIUS / 2;
GRect frame = new GRect(fx, fy, FRAME_WIDTH, FRAME_HEIGHT);
frame.setFilled(true);
frame.setColor(Color.GRAY);
add(frame);
add(createFilledCircle(cx, cy - dy, LAMP_RADIUS, Color.RED));
add(createFilledCircle(cx, cy, LAMP_RADIUS, Color.YELLOW));
add(createFilledCircle(cx, cy + dy, LAMP_RADIUS, Color.GREEN));
}
private GOval createFilledCircle(double x, double y, double r, Color color){
GOval circle = new GOval(x-r, y-r, 2 * r, 2 * r)
circle.setColor(color);
circle.setFilled(true);
return circle;
}
private static final double FRAME_WIDTH = 50;
private static final double FRAME_HEIGHT = 100;
private static final double LAMP_RADIUS = 10;
}
1. Am I right to assume cx and cy are to figure out the center of the page?
Yes
2. Are fx and fy to figure out the center of the frame?
Not exactly. They are computing the upper left hand corner of the frame. They start at the center and "back up" by half the frame size in each direction.
3. I don't know what dy does and why it's divided by 4 and not 3 for 3 lights and the LAMP_RADIUS totally confuses me.
Look farther down in the code. dy is the vertical distance between lights. The yellow light is drawn exactly at the center, the red is dy above, and the green is dy below. The divisor is 4 because the author chose to align the bottom edge of the red light with a point 1/4 of the frame height from the top of the frame. Similarly he chose to align the top of the green light with a point 1/4 of the frame height from the bottom. He could have chosen many other ways of computing dy.
4. On all three add(createFilledCircle) for red, yellow and green I don't understand how their position is calculated inside the stoplight frame.
They all have the same x-coordinate: the center of the frame. The y-coordinates are computed as explained in 3. Remember in screen coordinates, the positive direction is down, so increasing y puts a light lower. Decreasing puts it higher.
5. In the method createFilledCircle() I don't understand GOval circle = newGOval(x-r, y-r, 2 * r, 2 * r);. I don't understand what x-r and y-r does and how that relates to position.
Go read the manual definition of newGOval. It inscribes an oval shape inside a rectangle. The parameters are the upper left corner of the rectangle followed by the width and height. So if (x,y) is the center, this is giving a box with diagonal (x-r, y-r) to (x+r, y+r). When you inscribe an oval in that, you get a circle centered at (x,y) as desired.
Am I right to assume cx and cy are to figure out the center of the page?
Yes
Are fx and fy to figure out the center of the frame?
No, they're the top-left coordinate
I don't know what dy does and why it's divided by 4 and not 3 for 3 lights and the LAMP_RADIUS totally confuses me.
To fit three lights vertically inside a box you need one in the middle, one at 1/4 height, and one at 3/4 height - hence the division by four. I'm unsure why the LAMP_RADIUS comes into it. It appears to be what I'd normally call a "fudge factor" to make the lamps more widely spaced, i.e a figure that looks right, but without any good reason why it looks right...
On all three add(createFilledCircle) for red, yellow and green I don't understand how their position is calculated inside the stoplight frame.
They're just vertically spaced by dy
In the method createFilledCircle() I don't understand GOval circle = newGOval(x-r, y-r, 2 * r, 2 * r);. I don't understand what x-r and y-r does and how that relates to position.
The GOval puts a circle inside the box defined by the coordinates (x - r, y - r) with size 2r - i.e a square of side-length 2r centered on (x, y)

Put points round into circular arc used in java

I have me math question: I have known a circle center and radius, and have some uncertain number of points called N, my question is how to put the points on the circular arc, I cannot like put the points around the whole circumference, other as this link: http://i.6.cn/cvbnm/2c/93/b8/05543abdd33b198146d473a43e1049e6.png
in this link, you can read point is circle center, other color is some points, you can see these points around the arc.
Edit - in short: I have known a circle center and radius, so I want to generate some point around the circle center
I am not sure, but I checked this with simple Swing JComponent and seems ok.
Point center = new Point(100, 100); // circle center
int n = 5; // N
int r = 20; // radius
for (int i = 0; i < n; i++)
{
double fi = 2*Math.PI*i/n;
double x = r*Math.sin(fi + Math.PI) + center.getX();
double y = r*Math.cos(fi + Math.PI) + center.getY();
//g2.draw(new Line2D.Double(x, y, x, y));
}
It's not entirely clear what you're trying to accomplish here. The general idea of most of it is fairly simple though. There are 2*Pi radians in a circle, so once you've decided what part of a circle you want to arrange your points over, you multiply that percentage by 2*pi, and divide that result by the number of points to get the angle (in radians) between the points.
To get from angular distances to positions, you take the cosine and sine of the angle, and multiply each by the radius of the circle to get the x and y coordinate of the point relative to the center of the circle. For this purpose, an angle of 0 radians goes directly to the right from the center, and angles progress counter-clockwise from there.

Categories

Resources