I have trouble drawing a triangle with the draw(Graphics g) method in Java.
I can draw a rectangle like so:
public void draw(Graphics g) {
g.setColor(colorFill);
g.fillRect(p.x, p.y, width, height);
g.setColor(colorBorder);
g.drawRect(p.x, p.y, width, height);
drawHandles(g);
Where p represents "the top left corner of the shapes". How would I draw the triangle in the same manner?
Could someone give me an example for a standard triangle?
There is not a drawTriangle method neither in Graphics nor Graphics2D. You need to do it by yourself. You can draw three lines using the drawLine method or use one these methods:
drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
drawPolygon(Polygon p)
drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
These methods work with polygons. You may change the prefix draw to fill when you want to fill the polygon defined by the point set. I inserted the documentation links. Take a look to learn how to use them.
There is the GeneralPath class too. It can be used with Graphics2D, which is capable to draw Shapes. Take a look:
http://docs.oracle.com/javase/tutorial/2d/geometry/arbitrary.html
You should try using the Shapes API.
Take a look at JPanel repaint from another class which is all about drawing triangles, look to the getPath method for some ideas
You should also read up on GeneralPath & Drawing Arbitrary Shapes.
This method is much easy to apply AffineTransformations to
Use a line algorithm to connect point A with point C, and in an outer loop, let point A wander towards point B with the same line algorithm and with the wandering coordinates, repeat drawing that line. You can probably also include a z delta with which is also incremented iteratively. For the line algorithm, just calculate two or three slopes for the delta change of each coordinate and set one slope to 1 after changing the two others proportionally so they are below 1. This is very important for drawing closed geometrical areas between connected mesh particles. Take a look at the Qt Elastic Nodes example and now imagine drawing triangles between the nodes after stretching this over a skeleton.
As long as it will remain online
there is no command directly to draw Triangle. For Drawing of triangle we have to use the concept of lines here.
i.e, g.drawLines(Coordinates of points)
There is no direct method to draw a triangle.
You can use drawPolygon() method for this.
It takes three parameters in the following form:
drawPolygon(int x[],int y[], int number_of_points);
To draw a triangle:
(Specify the x coordinates in array x and y coordinates in array y and number of points which will be equal to the elements of both the arrays.Like in triangle you will have 3 x coordinates and 3 y coordinates which means you have 3 points in total.)
Suppose you want to draw the triangle using the following points:(100,50),(70,100),(130,100)
Do the following inside public void paint(Graphics g):
int x[]={100,70,130};
int y[]={50,100,100};
g.drawPolygon(x,y,3);
Similarly you can draw any shape using as many points as you want.
You can use Processing library:
https://processing.org/reference/PGraphics.html
There is a method called triangle():
g.triangle(x1,y1,x2,y2,x3,y3)
Related
How can I make the vertices of a polygon in libgdx?
I am trying to make a pentagon for collision detection and I am kind of confused about how the vertices part is done, until now I used rectangle to achieve this
You should make several polygons since a pentagon is a convex shape and not easy to compute if a point is within the shape.
To create a shape with the Polygon class you specify the vertices with a float array. In sequence, you specify the x and y positions. Since Polygon is a 2D shape in Libgdx the Z axis is not needed.
Below is a polygon for a triangle shape, create your pentagon like this from multiple polygons and use Intersector to test the polygon vs various other geometry like lines and points. Note, Intersector does contain method overlapConvexPolygon but I am pretty sure that gives true for something in between the points of your pentagon.
new Polygon(new Array[
0, 0,
10, 0,
5, 10
]);
I have an assignment to draw a certain number of circles using java.awt.Graphics.
Drawing the circles is fairly simple, but I am only supposed to draw the circle if it appears within the visible area. I know I can call method getClipBounds() to determine the drawing area, but I'm having trouble finding a java implementation of a way to determine if a circle intersects a Rectangle.
Is that the right way to go about determining if the circle I want to draw will be completely visible or is there a simpler way?
Don't use the Graphics.fillOval(...) method to do the painting.
Instead you can use the Graphics2D.fill(Shape) method. You can create oval Shape objects using the Ellipse2D class.
but I'm having trouble finding a java implementation of a way to determine if a circle intersects a Rectangle.
The Shape object has a method that will allow you to get the rectangular bounds of the Shape. Then you can use the Rectangle.contains(...) method of the your Graphics area to determine if the Shape is fully contained within your panel.
Check out Playing With Shapes for more information and ideas.
use Ellipse2D.Float to instanciate an object for example:
Shape circle = new Ellipse2D.Float(100.0f, 100.0f, 100.0f, 100.0f);
basically the parameters,from left to right, are: Height, Width, X of the Top left and Y of the top left, and by keeping the X and Y both greater or equal to zero, your circle will always be visible.
the parameters of the Float(...) are documented for the Ellipse2D.Float in Java SE 7 in
http://docs.oracle.com/javase/7/docs/api/java/awt/geom/Ellipse2D.Float.html
I have a class called Circle that extends from a class called Shape. I am trying to figure out how to get a circle to draw on a plotter using the given description of the draw() method.
Here's what I have so far for the class:
public class Circle extends Shape{
private double radius;
public Circle(double x_origin, double y_origin, double r, Color c){
super(x_origin, y_origin, c);
this.radius = r;
}
public void draw(WinPlotter plotter){
setPenColor(plotter);
}
}
The setPenColor just provides a color for the circle to be drawn, feel free to ignore it.
The javadoc description for the circle's draw method is as follows:
Draws the Circle. Uses sine and cosine functions from the
java.lang.Math class to compute a finite set of points that lie on the
circumference of a circle, and then uses the drawTo method of
WinPlotter to draw a sequence of small connected straight-line
segments. When enough segments are drawn (about 25 segments are
sufficient), a smooth circle is approximated.
If you need to see the entire Circle javadoc for it, here it is
Here is the WinPlotter javadoc to use as a reference. I have only been using the moveTo() and drawTo() methods for every other shape I have had to draw.
I just want to know the best way to draw a circle on the plotter.
Simple way I can think of is to use Math.sin and Math.cos to loop to 360 degress(2*PI) over a set interval, drawing lines between the current value and the previous one.
Look at http://en.wikipedia.org/wiki/Trigonometric_functions and check out the pictures on the right. Then think about it as a loop with your loop variable being thea
GL on your homework.
Edit: Heres the link you should really look at http://iopixels.com/cos-sin-explain
Hello for a school exercise i need to create a game and i decided to create Pacman. Everything goes well but one thing i can't accomplish is to draw a pacman dude and his ghosts.. i made and oval but what now? i want the pacman mouth also to open and close as it moves. can someone help drawing this?
below what i have till now:
package h04PacMan;
import java.awt.*;
public class DrawPacMan {
public void drawPacMan(Graphics g, int x, int y, Color color) {
g.setColor(color); // set color
g.fillOval(x, y, 50, 50); // paint
g.setColor(Color.black);
g.drawOval(x, y, 50, 50); // outline
// mouth?
}
public void drawGhost(Graphics g, int x, int y, Color color) {
g.setColor(color); // color
// here goes shape
}
}
Instead of using drawOval and fillOval, you should have a look at drawArc and fillArc.
See java.awt.Graphics.
Concerning the animation of the mouth: Given that pacman is constantly moving, you could combine pacman's position with a sine function to get a nice and smooth mouth movement, something like this:
angle = 20 * (Math.sin((x + y)*2*Math.PI/50) + 1); # alt. betw. 0 and 40
g.fillArc(x, y, 50, 50, angle/2, 360-angle);
This way, Pacman's mouth will automatically do one open-close-cycle as he moves a distance of his own size through the maze. (You may have to tweak the numbers a bit to fit your setup.)
Of course, you will still need a thread to run the game as a whole, but the animation of Pacman's mouth can be done this way, too, without extra threads.
So there are a couple of things going on here that you will need to address.
1. Drawing Characters
I'll only address drawing Pacman here.
Thinking about the Pacman game, Pacman's character has two states -- mouth closed, and mouth opened (in each cardinal direction!). This will be important for when we animate Pacman in a moment, so first, lets establish our pacman shape by using the fillArc method from the Graphics library.
Example of Mouth-Open Pacman:
g.setColor(Color.yellow);
g.fillArc(0,0,150,150,30,300);
This will create pacman in the top-left corner of your window, with pacman's mouth facing to the right of the screen. The last two paramters of the fillArc method control this opening -- the 5th parameter is the starting angle, and the sixth parameter is the angle of the full arc. You may infer from this that the start angle 0 is the horizontal line going from the center of the arc to the right of the screen. Also remember from mathematics that a full circle is 360 degrees.
Using this information, try drawing mouth-opened Pacman facing up, down and left. After you do that, fill the entire arc to draw Pacman with his mouth closed. Also consider other methods in the Graphics library you can use to draw your ghosts!
2. Animating Pacman
For this task you will probably want to implement some sort of Thread structure to animate Pacman, which gets quite a bit more complicated than what you've demonstrated here. Since we don't know your program specifications, and you also haven't demonstrated any code relating to the animation yet, I'm hesitant to lay this out any further. However, I will direct you to some links on the matter:
For a general overview, check out Java Tutorials - Concurrency.
If you're using Swing for this project, you may want to use SwingWorker for your threads.
I'd recommend taking advantage Area/Path2D API.
Have a look at Graphics 2D
You can have a look at the sample code in this answer for an example
I have a Graphics2D object which I use to draw on my Canvas. I draw multiple shapes on the Canvas and want to transform only one (or part) of them.
I'll try to keep this simple:
void render(Graphics2D g) {
... // Draw shape 1
... // Draw shape 2
... // Draw shape 3
}
How would I go about rotating shape 2 while leaving shape 1 and 3 intact? By "rotate" I mean rotating around its center point, which we can define as x and y for example.
I've been looking for a way to do this for a while now, but couldn't find anything that works the way I want it to.
Is there any simple way to do this?
Rather than rotating the shape around it's centre point, rotate and then translate the canvas. To rotate around the centre of the shape at (x, y), first translate the canvas by (-x, -y) and then rotate the canvas -d degrees and draw the shape as normal at (0,0).
When you're done, rotate back then translate back (note that with these geometric transformations the order is important, translating and then rotating will give you a completely different outcome).
This means that you can still draw an object at any rotation without having to recalculate the coordinates yourself.
AffineTransform afx = new AffineTransform();
afx.rotate(angleRad, s.getCenter().x, s.getCenter().y);
//afx.rotate(angleRad);
java.awt.Shape ss = afx.createTransformedShape(s.getPrimativeShape());
return ss;
s is my wrapper class for java.awt.Shape and does some stuff with it.... But what you want is in line 2.
afx.rotate(Angle,xAnchorPoint,yAnchorPoint);
afx.rotate rotates the object about the point (xAnchorPoint;yAnchorPoint).
Hope this is what you wanted
In order to rotate a shape, use one of the Graphics2D.rotate methods.
Cache the transform used for both shape 1 and shape 3. Before drawing shape 3, ensure that you reset the transform to the cached one, since using rotate for shape 2 will alter the current transform coordinates.
Steps:
Cache current transform
Draw shape 1
Rotate
Draw shape 2
Set transform to cached one
Draw shape 3