I am writing a simple game, or so it seemed. I created a class that draws a Arc2D (half a circle shape), that same class will repaint the arch as the mouse move.
Then I created a new class that draws ovals. This class has some simple mathematics to move the ovals on the screen. The movement of the ovals are not very important. So now that this is done I want to detect if the Oval collides with the arc(half a circle, Only the arc line) at any point.
What I have attempted is making the oval a Rectangle and use the intersect method. This code is in the draw method for the arc.
Arc2D temp= new Arc2D.Double(200, 200, 100, 100, angle, 180, Arc2D.OPEN);
MasterOval m = new MasterOval();
Rectangle r1 = m.bounds();//This gets the bounds of the oval
if(r1.intersects(temp.getBounds()))
System.out.println("hit");//display if intersects
For some reason I cant figure out why it will not display the word hit when it collides with the arc. Is there a way to see if they intercect? This is all code I can provide due to privacy policies. Please help.
Well, I'm not sure if your MasterOval class implements the Shape interface or not, but if it does (if it doesn't, consider using Ellipse2D.Double or something of that sort), the easiest way (standard perhaps ?) of checking for collision between Shape instances is using Area:
Shape1 shape1 = new Arc2D.Double(...);
Shape2 shape2 = new Ellipse2D.Double(...);
Area area1 = new Area(shape1);
Area area2 = new Area(shape2);
if (area1.intersect(area2)) {
...
}
Related
I am trying to make a snake game in java but the thing i am trying to make is not a normal snake game. I want to make a snake game which is snake (player) can go to every direction (like in slither.io game).
And i am trying to make a snake from circles.
I am trying to use Graphics2D for it and I successfully draw a circle.
But I couldnt make it lot of circles which is attached to eachothers. (I tryed to use arrayList).
Also like in classical snake game i want to make snake grow when it eats food.
But instead of making it longer i need to add more circles.
Code i wrote for the circle (script name is also "Circle");
public void drawToScreen(Graphics2D g)
{
g.setColor(GameConstants.BORDER_COLOR);
BasicStroke stroke = new BasicStroke(5);
g.setStroke(stroke);
Ellipse2D border = new Ellipse2D.Double(getX()-getSize()/2, getY()-getSize()/2, getSize(), getSize());
g.draw(border);
g.setColor(getColor());
Ellipse2D shape = new Ellipse2D.Double(getX()-getSize()/2, getY()-getSize()/2, getSize(), getSize());
g.fill(shape);
setBounds(shape.getBounds());
// Here is for the username
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.PLAIN, 14));
int width = g.getFontMetrics().stringWidth(getName());
g.drawString(getName(), (int)(getX()-width/2), (int)(getY()+5));
}
I have another script ("GamePanel") which I set up game, in that script I call some function whit this codes.
private Circle player;
player = new Circle(GameConstants.START_SIZE, spawnPoint.getX(), spawnPoint.getY(), randomColor(), GameConstants.START_VELOCITY, name);
player.drawToScreen(g2);
g2.translate(viewX, viewY);
I have zero clue what a "Script" is in Java.
But here is the source code to a game with very similar aspects that you can draw lessons from.
I made the Enemy ai a tad to intelligent, but you you will see how to do what you are asking in this code.
The Great Escape
So I have this program to test the possibility of an object to slide down in a ramp given its friction, object mass and ramp angle. However I need to animate the box if the force is positive. Just a simple animation moving the box from that point to the end of the ramp. But I can't. Please help
private void drawTransform(Graphics g, double modifier) {
// redtowhite = new GradientPaint(0,0,color.RED,100, 0,color.WHITE);
Rectangle rect = new Rectangle(130,350, 350, 15);
Rectangle box = new Rectangle((int) (rect.getX()+300), 300, 50, 50);
AffineTransform at = new AffineTransform();
at.rotate(-Math.toRadians(modifier), rect.getX(), rect.getY() + rect.height);
// Transform the shape and draw it to screen
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.DARK_GRAY);
// g2d.fillRect(0, 0, 350, 600);
g2d.fill(at.createTransformedShape(rect));
g2d.draw(at.createTransformedShape(box));
}
Screenshot:
If all you want to do is move the box, this can be done by simply updating it's X position. You should be able to manipulate the rectangle's X position directly using something like "box.x++". Alternatively you could create a variable and reference that to provide the initial X co-ordinate, then updating that variable will "move" the box. One issue is this will only move the box along the X axis, hence you will also need some kind of constant downward force acting as gravity. This is easy to achieve, just minus the box's Y position value when it is not colliding with the ground, or your ramp.
Another approach is velocity based movement using vectors, however you mentioned that the animation should be simple. If you do want a smoother animation velocity based movement will provide this but you will need to perform a little research first.
I've been looking for solutions in google with no success, I'm creating a small library (just a wrapper) for Box2D in LibGDX and I'm drawing a texture for each body, taking as base the Body.getPosition() vector, however, I see polygon's getPosition() is different respect to CircleShapes and the walls (which were created with setAsBox() method).
Here's an image:
http://i.stack.imgur.com/NzooG.png
The red points are the center of mass, the cyan circles are the geometric center (right?) given by body.getPosition(), as you can see I can adapt the texture to the body in terms of position, rotation and scale but this does not happen with polygons (except the ones made with setAsBox()).
Basically, what I want is to get the cyan circle in the AABB centre of the regular polygons. here's a runnable example:
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.math.Vector2;
public class MyGdxGame extends ApplicationAdapter {
Tabox2D t;
float w ,h;
#Override
public void create () {
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
t = Tabox2D.getInstance();
t.debug = true;
t.newBall("d", 100, 200, 25);// Ball.
t.newBox("s", 10, 10, w - 20, 50);// Floor.
t.newHeptagon("d", new Vector2(200, 200), 40);
}
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
t.update(0);// Don't move anything just to see the cyan circle.
t.draw();
}
}
Tabox2D class is here: https://github.com/tavuntu/tabox2d
NOTE: this was tested with the last version of Android Studio and LibGDX.
Thanks in advance!
Looks to me like you are positioning the shapes on the centre point, instead of the body. The centre of the shapes should be 0,0, not center.x,y. Fixture positions are relative to the body.
OK, so I think I solved this maybe in an inelegant way. What I did was:
Create the polygons points around the origin
Get AABB center of polygon and centroid (not necessarily the same)
Translate points to make AABB center the shape center, so the image can be drawn respect to this and not the center of mass.
The code needs a lot of cleaning but it seems to work just well, updated code in github repo, thanks!
The change was basically translate points from the original centroid to AABB center:
for(int i = 0; i < pts.length - 1; i += 2) {
pts[i] -= aabbCenter.x;
pts[i + 1] -= aabbCenter.y;
}
I needed to draw a Car using Java and Graphics2D. I used multiple basicstrokes to come up with the shape of the car. How do I fill it with color? An example would be drawing 3 lines in the shape of a triangle and then wanting to fill it with color.
You can not simply fill a shape that was only created by drawing three lines. You have to define the shape, including all the lines that it consists of.
How exactly this is implemented depends on serveal factors. For example, whether you want to use the same stroke for all three lines, or whether they need different strokes.
It could be helpful if you had already provided some information of how exactly you are drawing the lines at the moment. I'll try to make a guess here...
So assuming that your current code roughly looks like this:
void paintCar(Graphics2D g)
{
g.setStroke(new BasicStroke(1.0f));
g.setColor(Color.BLUE);
// Draw the triangle
g.drawLine(100,100,200,100);
g.drawLine(100,200,150, 50);
g.drawLine(150, 50,100,100);
}
the easiest way to additionally fill this triangle would be to change it as follows:
void paintCar(Graphics2D g)
{
g.setStroke(new BasicStroke(1.0f));
g.setColor(Color.BLUE);
Path2D path = new Path2D();
// Build the triangle
path.append(new Line2D.Double(100,100,200,100), false);
path.append(new Line2D.Double(100,200,150, 50), true);
path.append(new Line2D.Double(150, 50,100,100), true);
// Draw the triangle
g.draw(path);
// Fill the triangle, with a different color
g.setColor(Color.CYAN);
g.fill(path);
}
But note...
... that there are more elegant and concise ways of achieving this. Usually, one would not append individual Line2D segments, but simply use the Path2D to build the shape:
void paintCar(Graphics2D g)
{
g.setStroke(new BasicStroke(1.0f));
g.setColor(Color.BLUE);
// Build the triangle
Path2D path = new Path2D();
path.moveTo(100,100);
path.lineTo(200,100);
path.lineTo(150, 50);
path.closePath();
// Draw the triangle
g.draw(path);
// Fill the triangle, with a different color
g.setColor(Color.CYAN);
g.fill(path);
}
So if you have the coordinates of your shape in an appropriate form (maybe stored as a list of Point2D objects), you may more easily build a shape that you can draw and fill then.
Ok dear folks, i've got this question and i don't really know a certain way to solve it.
I'm doing like a "Paint application" in java, i know everything is ready, but I need to paint the shapes with Computer Graphics Algorithms.
So, the thing is, once the shape is painted in the container how could I convert it like sort of an "Object" to be able to select the shape and move it around (I have to move it with another algorithm) I just want to know how could I know that some random point clicked in the screen belongs to an object, knowing that, I would be able to fill it(with algorithm).
I was thinking that having a Point class, and a shape class, if i click on the screen, get the coordinates and look within all the shapes and their points, but this may not be very efficient.
Any ideas guys ?
Thanks for the help.
Here is some of my code:
public class Windows extends JFrame{
private JPanel panel;
private JLabel etiqueta,etiqueta2;
public Windows() {
initcomp();
}
public void initcomp()
{
panel = new JPanel();
panel.setBounds(50, 50, 300, 300);
etiqueta = new JLabel("Circulo Trigonometrico");
etiqueta.setBounds(20, 40, 200, 30);
etiqueta2 = new JLabel("Circulo Bresenham");
etiqueta2.setBounds(150, 110, 200, 30);
panel.setLayout(null);
panel.add(etiqueta);
panel.add(etiqueta2);
panel.setBackground(Color.gray);
this.add(panel);
this.setLayout(null);
this.setVisible(true);
this.setSize(400,400);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.red);
g2d.setStroke(new BasicStroke(2));
dibujarCirculo_bresenham(g2d, 50, 260, 260);
dibujarCirculo_trigonometrico(g2d, 50, 130, 200);
}
/*This functions paints a Circle*/
public void dibujarCirculo_trigonometrico(Graphics g,int R,int xc,int yc)
{
int x,y;
for (int i = 0; i < 180; i++) {
double angulo = Math.toRadians(i);
x = (int) (Math.cos(angulo)*R);
y = (int) (Math.sin(angulo)*R);
g.drawLine(x+xc, y+yc, x+xc, y+yc);
g.drawLine((-x+xc), (-y+yc), (-x+xc), (-y+yc));
}
}
I assume that any image is a valid (isn't constrained to a particular set of shapes). To get an contiguous area with similar properties, try using a flood fill.
To colour in or move a particular shape around, you can use flood fill to determine the set of pixels and manipulate the set accordingly. You can set a tolerance for similar hue, etc so that it's not as rigid as in Paint, and becomes more like the magic selection tool in Photoshop.
There are a couple of approaches to take here depending on what precisely you want.
1) is to have objects, one for each drawn thing on screen, with classes like Circle and Rectangle and Polygon so on. They would define methods like paint (how to draw them on screen), isCLickInsideOf (is a click at this point on screen contained by this shape, given size/position/etc?) and so on. Then, to redraw the screen draw each object, and to test if an object is being clicked on ask each object what it thinks.
2) is, if objects have the property of being uniform in colour, you can grab all pixels that make up a shape when the user clicks on one of the pixels by using a floodfill algorithm. Then you can load these into some kind of data structure, move them around as the user moves the mouse around, etc. Also, if every object is guaranteed to have a unique colour, you can test which object is being clicked on by just looking at colour. (Libraries like OpenGL use a trick like this sometimes to determine what object you have clicked on - drawing each object as a flat colour on a hidden frame and testing what pixel colour under the mouse pointer is)