Drawing a circle using lines in java - java

I'm currently trying to implement a draw method for a circle however my only tools are drawing lines from multiple points (specifcally for this example, I have a "pen" that i can move to, then draw from that location to a new location on a grid.)
This is my current code
public void draw(WinPlotter plotter){
setPenColor(plotter);
plotter.moveTo(xo,yo); //xo,yo being original X and Y cords (origin)
for (int i = 0; i > 360; i++){
double x = Math.sin(i) * radius;
double y = Math.cos(i) * radius;
plotter.drawTo(x,y);
}
}
I'm not sure what i'm missing, but this actually won't output anything at all, I've tested to make sure that xo and yo are being passed to the method properly, so i'm confident that my problem lies in my logic of trying to draw a circle from lines.
EDIT:
public void draw(WinPlotter plotter){
setPenColor(plotter);
plotter.moveTo(xo,yo+radius);
for (int i = 0; i <= 360; i++){
double x = xo+ Math.sin(i * (Math.PI / 180)) * radius;
double y = yo+ Math.cos(i) * radius;
plotter.drawTo(x,y);
}
}
This is my fixed code. Still does not create circles, instead creates this (the circles are supposed to be on the top)

Issue 1: sin() and cos() are expecting inputs in radians, not degrees. To get radians, multiply i by Math.PI / 180.
Issue 2: The conditional in your loop is backward; you want i < 360, not i > 360. If you want to close the circle, use i <= 360 instead.
Issue 3: You're not adding xo and yo to the calculated x/y coordinates, so you're drawing all of the circle except the first point at the (0, 0) origin.
Issue 4: Your initial moveTo() goes to the center of the circle instead of the point on the circle at 0 degrees.

Related

Move camera to the direction it's facing

I have a camera that has X, Y and Z Coordinates.
The camera also has a Yaw and a pitch.
int cameraX = Camera.getX();
int cameraY = Camera.getY();
int cameraZ = Camera.getZ();
int cameraYaw = Camera.getYaw();
int cameraPitch = Camera.getPitch();
The yaw has 2048 units in 360 degrees, so at 160 degrees the getYaw() method will return 1024.
Currently I move the camera forward by just setting the Y + 1 in each loop.
Camera.setY(Camera.getY() + 1);
How would I set the camera X and Y to the direction I'm facing (The Yaw)?
I don't want to use the pitch in this situation, just the Yaw.
If I understand your question correctly, you're trying to get the camera to move in the direction you're looking (in 2D space, you're only moving horizontally).
I made a small LookAt header-only library for C++, but here is part of it rewritten in Java. What this code does is it takes a rotation and a distance, then calculates how far you need to move (in both the x and y coordinate) to get there.
// Returns how far you need to move in X and Y to get to where you're looking
// Rotation is in degrees, distance is how far you want to move
public static double PolarToCartesianX(double rotation, double distance) {
return distance * Math.cos(rotation * (Math.PI / 180.0D));
}
public static double PolarToCartesianY(double rotation, double distance) {
return distance * Math.sin(rotation * (Math.PI / 180.0D));
}

Move in the same angle from point to point?

I need to be able to move my player x and y pixels in the same direction as a point to a point. It's hard to explain, but this is what I am trying to do:
Angles 1 and 2 have to be the same. Point 1 stays the same at (100, 100), however point 2 constantly changes and so must the angles. I have tried this:
moveRectangle.setX(touchEvent.getX());
moveRectangle.setY(touchEvent.getY());
float theta = (float) Math.toDegrees(Math.atan2(touchEvent.getY() - 100,touchEvent.getY() - 100));
float velX = (float) (getSpeed() * Math.cos(theta));
float velY = (float) (getSpeed() * Math.sin(theta));
player.move(velX, velY);
The above code is constantly run when the user puts his finger on moveRectangle (Point 2) and moves it. But the above code does not work. The player just moves in one of two directions. player.move just adds velX and velY velocity. So how can I get the two angles and move the player in the right direction? Thanks.
Would it be easier to approach this problem using a cartesian approach (vectors) versus polar approach (angle and magnitude)? So, if the player is at point p0 and the "finger" is at point p1, then the direction the player should be moving v is given by the vector p1-p0. You can then scale the resulting vector v by the player's speed, and add the player's speed to his position. You can do this easily on a frame-by-frame basis.
Do you need just to know velocity on X and Y axis? You can do it without using trigonometry (just use Pythagorean theorem).
final float deltaX = touchEvent.getX() - player.x; // player.x is point1.x
final float deltaY = touchEvent.getY() - player.y; // player.y is point1.y
final float length = Maths.sqrt((deltaX)^2 + (deltaY)^2);
final float itterations = length / getSpeed();
final float velX = deltaX / itterations;
final float velY = deltaY / itterations;
player.move(velX, velY);
Or you need a code of player moving in cycle?
Remove Math.toDegrees().
From the Math.sin() / cos() Javadoc:
Parameters:
a - an angle, in radians.
Returns:
the sine of the argument.

how to save values of variables and prevent them from changing when doing recursion? also recursion assistance?

import gpdraw.*;
public class Y2K {
// Attributes
SketchPad pad;
DrawingTool pen;
// Constructor
public Y2K() {
pad = new SketchPad(600, 600, 50);
pen = new DrawingTool(pad);
// Back the pen up so the Y is drawn in the middle of the screen
pen.up();
pen.setDirection(270);
pen.forward(150);
pen.down();
pen.setDirection(90);
}
public void drawY(int level, double length) {
// Base case: Draw an Y
if (level == 0) {
//pen.setDirection(90);
pen.forward(length);
pen.turnRight(60);
pen.forward(length);
pen.backward(length);
pen.turnLeft(120);
pen.forward(length);
pen.backward(length);
}
// Recursive case: Draw an L at each midpoint
// of the current L's segments
else {
//Drawing the bottom "leg" of our Y shape
pen.forward(length / 2);
double xpos1 = pen.getXPos();
double ypos1 = pen.getYPos();
double direction1 = pen.getDirection();
pen.turnRight(90);
drawY(level - 1, length / 2.0);
pen.up();
pen.move(xpos1, ypos1);
pen.setDirection(direction1);
pen.down();
pen.forward(length / 2);
double xpos2 = pen.getXPos();
double ypos2 = pen.getYPos();
double direction2 = pen.getDirection();
//Drawing upper Right Leg
pen.turnRight(60);
pen.forward(length / 2); //going to the midpoint
double xpos3 = pen.getXPos();
double ypos3 = pen.getYPos();
double direction3 = pen.getDirection();
pen.turnLeft(90);
drawY(level - 1, length / 2.0);
pen.up();
pen.move(xpos3, ypos3);
pen.setDirection(direction3);
pen.down();
pen.forward(length / 2);
//drawing upper left leg
pen.up();
pen.move(xpos1, ypos1);
pen.setDirection(direction1);
pen.down();
pen.forward(length / 2);
pen.turnLeft(60);
pen.forward(length / 2);
double xpos4 = pen.getXPos();
double ypos4 = pen.getYPos();
double direction4 = pen.getDirection();
pen.turnLeft(90);
drawY(level - 1, length / 2.0);
pen.up();
pen.move(xpos4, ypos4);
pen.setDirection(direction4);
pen.down();
pen.forward(length / 2);
pen.forward(length / 2);
}
}
public static void main(String[] args) {
Y2K fractal = new Y2K();
// Draw Y with given level and side length
fractal.drawY(8, 200);
}
}
output:
one certain leg of the triangle is too long, and that makes the output slightly off. maybe its because the code went (length/2) too far? lets debug this.
otherwise it is completely fine, the recursion is great, and its exactly what i wanted to do
As you're constantly drawing Y's, I'd recommend you create a method that draws a Y given certain parameters (e.g. length, angle of separation between the two branches of the Y, rotation, etc.). This will make your code much more readable and easier to understand.
As for moving to the center, just think of the Y on a coordinate plane. Based upon the rotation of the Y, and its starting point you can calculate the center point.
Just break it up into its x and y components.
Given this information, we can solve for a and for b.
a = length * sin(θ)
b = length * cos(θ)
Then add this to your x and y to calculate the center point of the Y.
As for keeping the constant length, you know the level. At the first level, level == 1. But the length of this next level should be length * (2^level). In this case, length/2 (as length would be -1).
In pseudo code terms:
public void drawY(int level, double length)
{
//Drawing the bottom "leg" of our Y shape
Move Forward length/2
Save our position
Save our direction
Turn to the right 90 degrees
Recursion (call drawY())
revert to original location
revert to original direction
move forward length/2 (to go to center point of Y)
save our new position
save our new direction
//Drawing upper Right Leg
Turn 60 to the right
Move Forward length/2 //going to the midpoint
save our new position (don't forget the center point)
save our new direction (don't forget the center point direction)
Turn 90 to the left
Recursion (call drawY())
return to our saved position (not center one)
return to our saved direction (not center one)
move forward length/2
//drawing upper left leg
return to center point
return to center direction
turn left 60
move forward length/2
save position (you can overwrite the center one now
save direction (you can overwrite)
turn left 90
Recursion (call drawY())
return to position
return to direction
move forward length/2
}

draw an angled square using sine and cosine

this is my first time posting on a forum. But I guess I will just jump in and ask.. I am trying to draw a rectangle with x, y, width, height, and angle. I do not want to create a graphics 2D object and use transforms. I'm thinking that's an inefficient way to go about it. I am trying to draw a square with rotation using a for loop to iterate to the squares width, drawing lines each iteration at the squares height. My understanding of trig is really lacking so... My current code draws a funky triangle. If there is another question like this with an answer sorry about the duplicate. If you have got any pointers on my coding I would love some corrections or pointers.
/Edit: Sorry about the lack of a question. I was needing to know how to use sine and cosine to draw a square or rectangle with a rotation centered at the top left of the square or rectangle. By using sin and cos with the angle to get the coordinates (x1,y1) then using the sin and cos functions with the angle plus 90 degrees to get the coordinates for (x2,y2). Using the counter variable to go from left to right drawing lines from top to bottom changing with the angle.
for (int s = 0; s < objWidth; s++){
int x1 = (int)(s*Math.cos(Math.toRadians(objAngle)));
int y1 = (int)(s*Math.sin(Math.toRadians(objAngle)));
int x2 = (int)((objWidth-s)*Math.cos(Math.toRadians(objAngle+90)));
int y2 = (int)((objHeight+s)*Math.sin(Math.toRadians(objAngle+90)));
b.setColor(new Color((int)gArray[s]));
b.drawLine(objX+x1, objY+y1, objX+x2, objY+y2);
}
It is called the Rotation matrix.
If your lines has the following coordinates before rotation:
line 1: (0, 0) - (0, height)
line 2: (1, 0) - (1, height)
...
line width: (width, 0) - (width, height)
Then applying the rotation matrix transform will help you:
for (int s = 0; s < objWidth; s++){
int x1 = cos(angle)*s
int y1 = sin(angle)*s
int x2 = s * cos(angle) - objHeight * sin(angle)
int y2 = s * sin(angle) + objHeight * cos(angle)
//the rest of code
}
Hope I didn't make a mistakes.
Do you mean like a "rhombus"? http://en.wikipedia.org/wiki/Rhombus (only standing, so to speak)
If so, you can just draw four lines, the horizontal ones differing in x by an amount of xdiff = height*tan(objAngle).
So that your rhombus will be made up by lines with points as
p1 = (objX,objY) (lower left corner)
p2 = (objX+xdiff,objY+height) (upper left corner)
p3 = (objX+xdiff+width,objY+height) (upper right corner)
p4 = (objX+xdiff+width,objY) (lower right corner)
and you will draw lines from p1 to p2 to p3 to p4 and back again to p1.
Or did you have some other shape in mind?

How do I draw an half Circle in opengl

I use this method which works perfectly to draw a full circle(might be typos in code text I wrote from memory):
drawCircle(GLAutodrawble drawble){
GL gl = drawble.getGL();
gl.glTranslatef(0.0f,0.0f,-7.0f);
gl.glBeginf(GL_LINE_LOOP);
gl.glColorf(0.0f,0.0f,0.0);
final dobule PI = 3.141592654;
double angle = 0.0;
int points = 100;
for(int i =0; i < points;i++){
angle = 2 * PI * i / points;
gl.glVertexf((float)Math.cos(angle),(float)Math.sin(angle));
}
gl.glScalef(1.0f,1.0f,0.0f);
gl.glEnd();
}
I want to use the same priciples to make method to make a half circle, I don't get my head around what I should do with the cos sin stuff. Can anyone take a look and help me.
Thanks goes to all that thakes a look at the problem!
Replace :
angle = 2 * PI * i / points;
With :
angle = PI * i / points;
Notice I removed the 2 multiplier as 2*PI is 360 (in degrees) which is a full circle. PI (180 degrees) is half a circle
Change this line:
angle = 2 * PI * i / points;
to this:
angle = 1 * PI * i / points;
Drawing circle is like the drawing a lines , connecting them. And the points should too close to each other to create a smooth curve.
you can use the following code to draw a half circle in opengl.
float PI = 3.14
float step=5.0;// How far is the next point i.e it should be small value
glBegin(GL_LINE_STRIP)
for(float angle=0.0f,angle<=180; angle+=step)
{
float rad = PI*angle/180;
x = centerX+radius*cos(rad);
y = centerY+radius*sin(rad);
glVertex(x,y,0.0f);
}
glEnd();

Categories