Im making a simple pong game and want to put a texture over my paddle but I don't know how to import image into my game. I tried doing in like here in 3rd example but it doesn't work:
Image myImage = getImage(getCodeBase(), "texture.png");
g.drawImage(myImage, 0, 0 , 10, 120, this);
g cannot be resolved
Here's some code:
public void run(){
Image myImage = getImage(getCodeBase(), "texture.png");
g.drawImage(myImage, 0, 0 , 10, 120, this);
GOval ball = makeBall();
add(ball);
GRect paddleLeft = makePaddle();
GRect paddleRight = makePaddle();
add(paddleLeft);
add(paddleRight);
bounce(ball, paddleLeft, paddleRight);
}
public static GRect makePaddle(){
GRect result = new GRect(0,0,WIDTH,HEIGHT);
result.setFilled(true);
result.setColor(Color.BLACK);
return result;
}
the texture.png is for the paddles
EDIT:
I got the texture to load, but I can't make it move with the paddles, I don't know why
WIDTH is width of the paddle, getWidth() - window. I guess the code I use to move the paddle should work for the texture but it doesnt
with the image.sendToFront() player's paddle's texture works, but the AI's doesn't
if(mouseY<getHeight()-HEIGHT){ // Player
paddleLeft.setLocation(WIDTH,mouseY);
image.setLocation(WIDTH,mouseY);
image.sendToFront();
}
else{
paddleLeft.setLocation(WIDTH,getHeight()-HEIGHT);
image.setLocation(WIDTH,getHeight()-HEIGHT);
image.sendToFront();
}
if(ball.getY()<getHeight()-paddleRight.getHeight()){ // AI
paddleRight.setLocation(getWidth()-2*WIDTH,ball.getY());
image2.setLocation(getWidth()-2*WIDTH,ball.getY());
image2.sendToFront();
}
else
paddleRight.setLocation(getWidth()-2*WIDTH,getHeight()-paddleRight.getHeight());
image2.setLocation(getWidth()-2*WIDTH,getHeight()-paddleRight.getHeight());
image2.sendToFront();
It seems like you are using a library from http://cs.stanford.edu/people/eroberts/jtf/ (based on the GRect class etc).
And it seems like you should be able to use a GImage as well. So the code could roughly look like
Image myImage = getImage(getCodeBase(), "texture.png");
//g.drawImage(myImage, 0, 0 , 10, 120, this);
GImage image = new GImage(myImage);
add(image);
Related
#Override
public void create()
{
batch = new SpriteBatch();
shape = new ShapeRenderer();
velocity = new Vector2(100, 0);
position = new Rectangle(0, 5, 100, 100);
font = new BitmapFont();
font.setColor(Color.BLACK);
font.getData().scale(3f);
camera = new OrthographicCamera();
confCamera();
}
#Override
public void render()
{
if(Gdx.input.isTouched())
position.x = Gdx.input.getX() - position.width/2;
position.y = (Gdx.input.getY() - position.height/2);
shape.begin(ShapeRenderer.ShapeType.Filled);
shape.setColor(Color.BLACK);
shape.rect(position.x, position.y, position.width, position.height);
shape.end();
}
It's a simple code, but I'm not undestanding Y axis, my shape moves like a mirror. If I touch on top, my shape goes to bottom. If I touch on bottom, my shape goes to top. How to fix it?
LibGDX (by default) for rendering uses coordinate system where 0 is at bottom of the screen and the more you go up Y coordinate grows.
Also, when you read input coordinates (touches, moves...) you get screen coordinates, but when you render your graphics you are using "world" coordinates. They are in 2 different coordinate system so to convert from screen to world you have to use camera.unproject() call. Should be like:
Vector3 touchPos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
and then use touchPos.x and touchPos.y.
The similar question is asked here so you can find more answers there:
Using unProject correctly in Java Libgdx
I'm attempting to draw a transparent mask of combined shapes over the top of an already in place image. I have provided an example of the techniques I'm trying via the dialog code included in this post. Here's a screenshot of what it produces.
Example 1 (top left) highlights the problem I want to solve, I wish to have the 2 circles Or any intersecting shapes/arcs, all draw together with the same level of alpha, ie without the compounding opaqueness caused by drawing over the top of each other.
Example 3 (bottom left) is my attempt to resolve the issue by creating a separate image with solid shapes on, then making that entire image transparent, what happens i think is that using this technique makes an image where the White is treated as the transparent colour, so the edge of the circle is blended with white so that when you draw it on it causes a "halo" effect around the shape.
Example 2 (top left) highlights this issue further by drawing the circles in the image as transparent too, so you can see the more pink colour caused by the highlight.
My question is, without any knowledge of the background colour, and without turning anti-aliasing off, how can I achieve the effect I am trying for? Is there a way, because all my research is coming up blank? Maybe I need to use a different image drawing solution and port back to SWT? I know it's capable of drawing Transparent images if loaded directly from a file so I know it can hold this sort of data, but how do I create it?
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class FMLDialog extends Dialog
{
private Color red;
private Color blue;
public FMLDialog(Shell parentShell)
{
super(parentShell);
}
#Override
protected void configureShell(Shell shell)
{
red = new Color(shell.getDisplay(), new RGB(255,0,0));
blue = new Color(shell.getDisplay(), new RGB(0,100,255));
super.configureShell(shell);
shell.setSize(new Point(450,550));
shell.setText("FML");
}
#Override
public Control createDialogArea(final Composite comp)
{
Composite content = (Composite) super.createDialogArea(comp);
Composite parent = new Composite(content, SWT.NONE);
GridLayout gridLayout2 = new GridLayout(1, false);
parent.setLayout(gridLayout2);
parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
final Canvas c = new Canvas(parent, SWT.BORDER);
c.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
c.addPaintListener(new PaintListener() {
#Override
public void paintControl(PaintEvent e) {
e.gc.setAntialias(SWT.ON);
drawFirstLayer(e.gc, 0, 0);
drawFirstLayer(e.gc, 210, 0);
drawFirstLayer(e.gc, 210, 210);
drawFirstLayer(e.gc, 0, 210);
drawSecondLayerTake1(e.gc, 0, 0);
drawSecondLayerTake2(e.gc, 210, 0);
drawSecondLayerTake3(e.gc, 0, 210);
drawSecondLayerTake4(e.gc, 210, 210);
}
});
return content;
}
private void drawFirstLayer(GC gc, int x, int y) {
gc.setBackground(blue);
gc.fillOval(x, y, 200 , 200);
}
private void drawSecondLayerTake1(GC gc, int x, int y) {
// Simply draw 2 transparent circles
// Issue here is the overlap between circles where the Alpha layers up
gc.setAlpha(100);
gc.setBackground(red);
gc.fillOval(x + 70, y + 70, 60 , 60);
gc.fillOval(x + 100, y + 100, 60 , 60);
gc.setAlpha(255);
}
private void drawSecondLayerTake2(GC gc, int x, int y) {
// Create an image with 2 transparent circles
// Issue here is the overlap between circles where the Alpha layers up from the first
// PLUS becasue my transparent colour is fixed to white the alpa on the circles is blended in to the white
final Image src = new Image(null, 300, 300);
final ImageData imageData = src.getImageData();
imageData.transparentPixel = imageData.getPixel(0, 0);
src.dispose();
final Image processedImage = new Image(Display.getCurrent(), imageData);
final GC imageGC = new GC(processedImage);
imageGC.setAntialias(SWT.ON);
imageGC.setAlpha(100);
imageGC.setBackground(red);
imageGC.fillOval(70, 70, 60 , 60);
imageGC.fillOval(100, 100, 60 , 60);
imageGC.dispose();
gc.drawImage(processedImage, x + 0, y + 0);
}
private void drawSecondLayerTake3(GC gc, int x, int y) {
// Create an image with 2 solid circles, then draw that image on to the canvas with Alpha values.
// Overlap issue goes away because the whole image is being made transparent together HOWEVER
// there is a Halo effect around the edge of the red where the original circles were antialiased to blend into the "white"
// background.
final Image src = new Image(null, 300, 300);
final ImageData imageData = src.getImageData();
imageData.transparentPixel = imageData.getPixel(0, 0);
src.dispose();
final Image processedImage = new Image(Display.getCurrent(), imageData);
final GC imageGC = new GC(processedImage);
imageGC.setAntialias(SWT.ON);
imageGC.setBackground(red);
imageGC.fillOval(70, 70, 60 , 60);
imageGC.fillOval(100, 100, 60 , 60);
imageGC.dispose();
gc.setAlpha(100);
gc.drawImage(processedImage, x + 0, y + 0);
}
private void drawSecondLayerTake4(GC gc, int x, int y) {
// I need this one to draw like take 3 but without the white "halo" effect on the edge
// How?!
}
public static void main(String[] args) {
Display d = new Display();
Shell s = new Shell();
FMLDialog fml = new FMLDialog(s);
fml.open();
}
}
I was able to get the desired result using the method described by Sean Bright here: https://stackoverflow.com/a/15685473/6245535.
Basically:
we create an image src and with gc we fill it with transparent color
we draw the ovals with solid color
we get the resulting image data: now, the pixel data array of the image (imageData.data) is also going to contain the alpha values, while the alpha data array of the image (imageData.alphaData) is null
we manually fix imageData.alphaData by extracting the alpha values at the right positions from imageData.data; this part assumes that we are working with 32 bit depth of color; it won't work otherwise
now that the alphaData of imageData is fixed, we create an image processedImage with it
with gc we finally draw processedImage with partial transparency
Here's the code (which is Sean's code with some changes):
private void drawSecondLayerTake4(GC gc, int x, int y) {
final int width = 300;
final int height = 300;
final Image src = new Image(null, width, height);
final GC imageGC = new GC(src);
imageGC.setAntialias(SWT.ON);
// This sets the alpha on the entire canvas to transparent
imageGC.setAlpha(0);
imageGC.fillRectangle(0, 0, width, height);
// Reset our alpha and draw the ovals
imageGC.setAlpha(255);
imageGC.setBackground(red);
imageGC.fillOval(70, 70, 60, 60);
imageGC.fillOval(100, 100, 60, 60);
// We're done with the GC, so dispose of it
imageGC.dispose();
final ImageData imageData = src.getImageData();
imageData.alphaData = new byte[width * height];
// This is the hacky bit that is making assumptions about
// the underlying ImageData. In my case it is 32 bit data
// so every 4th byte in the data array is the alpha for that
// pixel...
for (int idx = 0; idx < (width * height); idx++) {
final int coord = (idx * 4) + 3;
imageData.alphaData[idx] = imageData.data[coord];
}
// Now that we've set the alphaData, we can create our
// final image
final Image processedImage = new Image(Display.getCurrent(), imageData);
gc.setAlpha(100);
gc.drawImage(processedImage, x + 0, y + 0);
// And get rid of the canvas
src.dispose();
}
And here's the result:
You can use a Path to merge the 2 circles in a single entity and then fill it with the transparent color.
It is a much simpler solution than my previous answer and there is no halo effect.
The code:
private void drawSecondLayerTake4(GC gc, int x, int y) {
final Path path = new Path(Display.getCurrent());
path.addArc(x + 70, y + 70, 60, 60, 0, 360);
path.addArc(x + 100, y + 100, 60, 60, 0, 360);
gc.setAlpha(100);
gc.setBackground(red);
// needed to avoid holes in the path
gc.setFillRule(SWT.FILL_WINDING);
gc.fillPath(path);
path.dispose();
}
And the result:
I am somewhat new to java, and I'm trying to make a game that has large "pixels" that are actually 5*5 pixels large. I have tried to turn the graphics into an image and then resize the image, but it always returns a huge amount of errors. I am implementing ActionListener and using timer to create a game loop, if that means anything important.
I have the variable screen set as a createVolatileImage(160, 160);
public void actionPerformed(ActionEvent e) {
timer.start();
Graphics draw = screen.getGraphics();
draw.setColor(new Color(50, 100, 50));
draw.fillRect(0, 0, 100, 100);
draw.setColor(Color.black);
draw.drawString("Text",10,10);
draw = getGraphics();
draw.drawImage(screen, 0, 0, 800, 800, 0, 0, 160, 160, null);
draw.dispose();
}
My teacher is having us write code to draw a logo on the screen using awt, swing, and the graphics class. I decided to draw the google drive symbol, but I am getting stuck on the yellow third.
public class DriveLogo extends JApplet
{
public void init()
{
JRootPane rootPane = this.getRootPane();
rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
}
public void paint(Graphics g)
{
int num_rect_points = 4;
g.setColor(Color.black);
g.fillRect(0,0,getSize().width, getSize().height);
/*************************************Yellow 1/3**********************************/
//Order of vertices: Left, right, lower-right, lower-left
int p1x1 = 150, p1x2 = 250, p1x3 = 350, p1x4 = 300;
int p1y1 = 25, p1y2 = 25, p1y3 = 280, p1y4 = 280;
int[] poly_1_x = {
p1x1, p1x2, p1x3, p1x4
};
int[] poly_1_y = {
p1y1, p1y2, p1y3, p1y4
};
Polygon yellow = new Polygon(poly_1_x, poly_1_y, num_rect_points);
/*************************************Draw**********************************/
g.setColor(Color.yellow);
g.fillPolygon(yellow);
}
}
This produces the following result:
There should be a yellow rhombus/rectangle slanted to the left. I asked my teacher, and she reviewed my code, but could not isolate the problem, and told me it "should" be working. Should doesn't mean it is however, and this is a rather large grade. Spent most of two class periods and downloaded the project to my home computer to debug, but I just can't seem to figure out what the problem is.
Things I know; the polygon coordinates must be in order, so to draw a rectangle, I cannot list them top-left, bottom-right, bottom-left, top-right, but I can list them top-left, top-right, bottom-right, bottom-left.
Okay, I solved this by experimenting around. For whatever reason, the call to g.fillPolygon(Polygon p) was not working, but when I called g.fillPolygon(poly_1_x, poly_1_y, num_recto_points); it worked properly.
I'm currently working on a program in class, but got stuck at a point where I have to use a for loop to draw the lines of the cube. Can anyone help me out a little here? I've looked online for help, but couldn't get help on this program using a FOR loop.
Original Question:
Write an application that draws a cube. Use class GeneralPath and method draw of class Graphics2D.
This is what I have down so far:
import java.awt.Color;
import java.awt.geom.GeneralPath;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class CubeJPanel extends JPanel
{
public void paintComponent( Graphics g )
{
super.paintComponent( g );
// base one: coordinates for front of the cube, point 0, 1, 2, 3, 4
int base1X[] = { 100, 100, 200, 200, 100 };
int base1Y[] = { 100, 200, 200, 100, 100 };
// base two: coordinates for back of the cube, point 0, 1, 2, 3, 4
int base2X[] = { 75, 75, 175, 175, 75 };
int base2Y[] = { 75, 175, 175 ,75, 75 };
Graphics2D g2d = ( Graphics2D ) g;
g2d.setColor( Color.red );
GeneralPath cube = new GeneralPath();
// this is where i'm having trouble. I know i'm suppose to for loop and arrays to draw out the lines of the cube.
g2d.draw( cube );
} // end method paintComponent
} // end class CubeJPanel
The base1X, base1Y are x coordinates along a drawing area, with (0,0) being the top left corner of the panel. To use a GeneralPath you need to something like this:
GeneralPath cube = new GeneralPath();
cube.moveTo(base1x[0], base1y[0]);
for(int i=1; i<base1x.length(); i++)
{
cube.lineTo(base1x[i], base1y[i]);
}
cube.closePath();
The above code segment will draw a single square, which are all of the points in base1. Basically think of GeneralPath as connect the dots. You first have to move the path to a starting location. moveTo will move the drawer to the point, without drawing a line. The lineTo will draw a line from your current point to the point in the moveTo. Lastly, be sure to close the path.
Figure out the correct order to draw the points and you should be able to figure out how to iterate over the points.