Java paint program double buffering - java

So I'm working on a paint program in school and now I have to double buffer it. After a week of searching and using tutorials online I am still unable to double buffer my program properly... I have written a double buffer function but then you can't paint anything... When i disable the double buffer you can paint fine but the screen flickers. Please help
(Yes I am aware that some of my code is deprecated and I should fix that)
Code:
import java.applet.*;
import java.awt.*;
public class PaintRun extends Applet
{
static int posx = 0;
static int posy = 0;
static int posxOld = 0;
static int posyOld = 0;
static int size = 20;
static int toolNum = 0;
static boolean ready = false;
static Color col = new Color(120,120,120);
static Button clear = new Button(0,0,20,'C');
static Button sizeInc = new Button(20,0,20,'+');
static Button sizeDec = new Button(40,0,20,'-');
static Tools tool = new Tools(posx,posy);
public void paint(Graphics g)
{
drawButtons(g);
detectButtons(g);
}
private static void detectButtons(Graphics g)
{
if (clear.detect(posx,posy) == true)
{
g.setColor(Color.WHITE);
g.fillRect(0, 0, 800000, 800000);
drawButtons(g);
}
else if (sizeInc.detect(posx, posy))
{
size+=2;
drawButtons(g);
}
else if (sizeDec.detect(posx, posy))
{
size-=2;
if (size <= 2)
size = 2;
drawButtons(g);
}
else
{
if (ready == true)
{
g.setColor(Color.BLACK);
g.drawLine(posxOld, posyOld, posx, posy);
drawButtons(g);
}
}
}
private static void drawButtons(Graphics g)
{
clear.setColor(col, Color.BLACK);
sizeInc.setColor(col, Color.BLACK);
sizeDec.setColor(col, Color.BLACK);
clear.drawButton(g);
sizeInc.drawButton(g);
sizeDec.drawButton(g);
}
public boolean mouseDown(Event e, int x, int y)
{
posx = x;
posy = y;
posxOld = x;
posyOld = y;
ready = true;
repaint();
return true;
}
public boolean mouseDrag(Event e, int x, int y)
{
posxOld = posx;
posyOld = posy;
posx = x;
posy = y;
repaint();
return true;
}
// Normal Update function
public void update(Graphics g)
{
paint(g);
}
// Double buffered Update function
/*public void update(Graphics g)
{
Graphics offgc;
Image offscreen = null;
Dimension d = size();
offscreen = createImage(d.width, d.height);
offgc = offscreen.getGraphics();
offgc.setColor(getBackground());
offgc.fillRect(0, 0, d.width, d.height);
offgc.setColor(getForeground());
paint(offgc);
g.drawImage(offscreen, 0, 0, this);
}
*/
}
class Button extends Applet
{
int minX; // X coord where the button is drawn
int minY; // Y coord where the button is drawn
int maxX; // X size
int maxY; // Y size
char letter;
Color back;
Color line;
// Constructor block
public Button(char desc)
{
minX = 0;
minY = 0;
maxX = 40;
maxY = 40;
back = new Color(255,255,255);
line = new Color(0,0,0);
letter = desc;
}
public Button(int x, int y, char desc)
{
minX = x;
minY = y;
maxX = 40;
maxY = 40;
back = new Color(255,255,255);
line = new Color(0,0,0);
letter = desc;
}
public Button(int x, int y, int size, char desc)
{
minX = x;
minY = y;
maxX = size;
maxY = size;
back = new Color(255,255,255);
line = new Color(0,0,0);
letter = desc;
}
public Button(int x, int y, int sizeX, int sizeY, char desc)
{
minX = x;
minY = y;
maxX = sizeX;
maxY = sizeY;
back = new Color(255,255,255);
line = new Color(0,0,0);
letter = desc;
}
// Draws the button
public void drawButton(Graphics g)
{
g.setColor(back);
g.fillRect(minX, minY, maxX, maxY);
g.setColor(line);
g.drawRect(minX, minY, maxX, maxY);
g.drawString(Character.toString(letter), (minX+maxX/2)-4, (minY+maxY/2)+4);
}
// Sets the button colors
public void setColor(Color b, Color l)
{
back = b;
line = l;
}
// Detects if those coordinates are in the button location or not
public boolean detect(int x, int y)
{
boolean flag = false;
if (x > minX && x < (minX + maxX) && y > minY && y < (minY + maxY))
flag = true;
else
flag = false;
return flag;
}
}

Related

Draw intersection of two regions in JavaFX

I have a few restrictions type of a ax+by>=c (1) and x>=z and y>=k (2). Restrictions (1) and (2) make a regions. I need to find the intersection of this regions and fill that other color. How can I do it in JavaFX? Can I use Canvas for solve this?
Sure, just fill everything with the polygon color and then for each area fill everything not in the area with the background color.
Note that this way you fill the whole Canvas except for the polygon with the background color.
public class Area {
private final double x;
private final double y;
private final double threshold;
private final int minCorner;
public Area(double x, double y, double threshold, boolean greater) {
if (x == 0 && y == 0) {
throw new IllegalArgumentException();
}
if (greater) {
x *= -1;
y *= -1;
threshold *= -1;
}
this.x = x;
this.y = y;
this.threshold = threshold;
boolean yPos = y > 0;
// find corner with minimum result for evaluate
this.minCorner = x < 0 ? (yPos ? 1 : 2) : (yPos ? 0 : 3);
}
public Area(double x, double y, double threshold) {
this(x, y, threshold, false);
}
private static final int[][] CORNER_FACTORS = {
{0, 0},
{1, 0},
{1, 1},
{0, 1}
};
public boolean contains(double x, double y) {
return evaluate(x, y) <= threshold;
}
public double hLineIntersection(double y) {
if (x == 0) {
return this.y * y == threshold ? Double.POSITIVE_INFINITY : Double.NaN;
} else {
return (threshold - this.y * y) / this.x;
}
}
public double vLineIntersection(double x) {
if (y == 0) {
return this.x * x == threshold ? Double.POSITIVE_INFINITY : Double.NaN;
} else {
return (threshold - this.x * x) / this.y;
}
}
private double evaluate(double x, double y) {
return this.x * x + this.y * y;
}
public void fillCleanArea(GraphicsContext gc, double w, double h) {
double[] xcoords = new double[5];
double[] ycoords = new double[5];
int[] factors = CORNER_FACTORS[minCorner];
boolean inside = contains(factors[0] * w, factors[1] * h);
int ptIndex = 0;
for (int i = minCorner, max = minCorner + 4; i < max; i++) {
factors = CORNER_FACTORS[i % 4];
double x = factors[0] * w;
double y = factors[1] * h;
boolean nowInside = contains(x, y);
if (inside != nowInside) {
// add intersection point with side
if ((i & 1) == 0) {
ycoords[ptIndex] = vLineIntersection(x);
xcoords[ptIndex++] = x;
} else {
xcoords[ptIndex] = hLineIntersection(y);
ycoords[ptIndex++] = y;
}
inside = nowInside;
// stop, if the end point is inside the area again
if (inside) {
break;
}
}
// add corners outside the bounds to polygon
if (!inside) {
xcoords[ptIndex] = x;
ycoords[ptIndex++] = y;
}
}
// draw polygon
if (ptIndex > 0) {
gc.fillPolygon(xcoords, ycoords, ptIndex);
}
}
}
public static void draw(Canvas canvas, Paint fill, Paint background, Area... areas) {
GraphicsContext gc = canvas.getGraphicsContext2D();
double w = canvas.getWidth();
double h = canvas.getHeight();
// fill everything with polygon color
gc.setFill(fill);
gc.fillRect(0, 0, w, h);
// fill everything outside the polygon with background color
gc.setFill(background);
for (Area area : areas) {
area.fillCleanArea(gc, w, h);
}
}
#Override
public void start(Stage primaryStage) {
Canvas canvas = new Canvas(400, 400);
draw(canvas, Color.BLUE, Color.WHITE,
new Area(1, 1, 400), new Area(1, -1, 100), new Area(1, -1, -100, true), new Area(1, 2, 250, true));
StackPane root = new StackPane(canvas);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
This won't give you the polygon's corner points though...

Draw lines between points, each moving in random direction

I'm working on a Java Game using LWJGL. I made a particle system and would like to obtain same result as found on this website: http://play.cubedpixels.de
This is what I got so far:
I tried my best and the problem is it's stopping and they are only moving in one direction. Also the lines are not like on this website. On the website it's smoother and better. They are using OpenGL too.
How to solve these problems and make my implementation better, more like it is one the website?
The code below shows two classes: ParticleGalaxy and Particle. Latter one is inner class of the former, but for clarity I've split them into separate snippets.
ParticleGalaxy:
public class ParticleGalaxy
{
private int count;
private int width;
private int height;
private int mousex;
private int mousey;
public ArrayList<Particle> particles = new ArrayList();
private Random random = new Random();
private TimerUtil timer = new TimerUtil();
int state = 0;
int a = 255;
int r = 255;
int g = 0;
int b = 0;
public ParticleGalaxy(int count, int width, int height)
{
this.count = count;
this.width = width;
this.height = height;
for(int i = 0; i < count; i++)
{
this.particles.add(
new Particle(this.random.nextInt(width),
this.random.nextInt(height)));
}
}
public void drawParticles(int mousex, int mousey)
{
this.mousex = mousex;
this.mousey = mousey;
for(Particle p : this.particles)
{
if(p.reset)
{
p.resetPosSize();
p.reset = false;
}
int x = Math.abs(p.getX() - mousex);
int y = Math.abs(p.getY() - mousey);
if((x < 40 && x > -40) && (y<35 && y>-40))
{
p.setConnect(true);
}
else
{
p.setConnect(false);
}
p.draw();
}
}
}
Particle:
public class Particle
{
private int x;
private int y;
private int k;
private int movey;
private int movex;
private int starty;
private int startx;
private int locationy;
private int locationx;
private float size;
private boolean reset;
private boolean connect;
private Random random = new Random();
private TimerUtil timer = new TimerUtil();
private boolean moving = false;
private boolean start = false;
public Particle(int x, int y)
{
this.x = x;
this.y = y;
this.startx = x;
this.starty = y;
this.size = genRandom(0.57F, 0.71F);
}
public void setConnect(boolean bool)
{
connect = bool;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
private void drawLine(int xto, int yto, int xfrom, int yfrom)
{
GL11.glLineWidth(1.2f);
GL11.glColor3f(1.0f, 1.0f, 1.0f);
GL11.glBegin(GL11.GL_LINE_STRIP);
GL11.glVertex2d(xto, yto);
GL11.glVertex2d(xfrom, yfrom);
GL11.glEnd();
}
public void draw()
{
if(!start)
{
start = true;
movex = height - random.nextInt(height);
movey = width - random.nextInt(width);
move(startx, starty, movex, movey);
}
float speed = 1;
float elapsed = 0.01f;
// On starting movement
float distance = (float)Math.sqrt(Math.pow(movex - startx, 2) +
Math.pow(movey - starty, 2));
float directionX = (movex - startx) / distance;
float directionY = (movey - starty) / distance;
if(moving == true)
{
x += directionX * speed * elapsed;
y += directionY * speed * elapsed;
if(Math.sqrt(Math.pow(x - startx, 2) + Math.pow(y - starty, 2)) >= distance)
{
x = (int)movex;
y = (int)movey;
resetPosSize();
this.reset = true;
moving = false;
}
}
this.k += 1;
int xx = 0;
int yy = 0;
this.locationx = this.x + xx;
this.locationy = this.y + yy;
if(locationx < 0 || locationy < 0)
this.reset = true;
if(locationx > width || locationy > height)
this.reset = true;
GuiUtils.drawCircle(this.x + xx, this.y + yy, this.size, -1);
if(connect)
{
for(Particle p : particles)
{
if(p.connect)
drawLine(locationx, locationy, p.locationx, p.locationy);
}
}
}
public void move(int startX, int startY, int endX, int endY)
{
x = (int)startX;
y = (int)startY;
moving = true;
}
public void resetPosSize()
{
this.x = this.random.nextInt(ParticleGalaxy.this.width);
this.y = this.random.nextInt(ParticleGalaxy.this.height);
startx = x;
starty = y;
movex = height - random.nextInt(height);
movey = width - random.nextInt(width);
move(startx, starty, movex, movey);
}
public float genRandom(float min, float max)
{
return (float)(min + Math.random() * (max - min + 1.0F));
}
}

Create multiple of 1 objects next to each other (grid like)

Hey if i have a simple rectangle class, how can i make it so that it creates that rectangle next to each other in a grid like pattern? maybe like 10 rows 10 columns?
public class Vak {
private int posX = 0;
private int posY = 0;
private int width = 50;
private int height = 50;
private Color colour;
public Vak(Color c, int x, int y){
this.colour = c;
this.posX = x;
this.posY = y;
}
public int vakPosY(){
return this.posY;
}
public int vakPosX(){
return this.posX;
}
public void draw (Graphics g){
g.setColor(this.colour);
g.drawRect(posX, posY, width, height);
}
public void move(int numberPixelsX, int numberPixelsY){
this.posX = this.posX + numberPixelsX;
this.posY = this.posY + numberPixelsY;
}
}
this is my code for rectangle "vak"
Is this what you are looking for?
int mapWidth = 10;
int mapHeight = 10;
// tileWidth and tileHeight should probably be public static const fields or static readonly properties of some class, but I put them here for now.
int tileWidth = 50; // Pixels
int tileHeight = 50; // Pixels
// tiles should probably be a field of a Map class (if you have one)
Vak[][] tiles = new Vak[mapWidth][mapHeight];
for(int x = 0; x < mapWidth; x++)
{
for(int y = 0; y < mapHeight; y++)
{
tiles[x][y] = new Vak(Color.white, x*tileWidth, y*tileHeight);
}
}
And then in the drawing part of the main loop:
for(Vak[] row : tiles)
{
for(Vak tile : row)
{
tile.draw(g);
}
}

Raytracing: Dark rings appear

I am getting strange rings of black on my spheres when I render with lighting. I just added lighting and I cannot figure out why the black rings are being created.
Here is my code for my tracer.
public class Tracer {
public Camera Cam;
public int Width, Height;
public BufferedImage Image;
public Color BackGroundColor;
public int StartX, StartY, EndX, EndY,RowCount,ColCount;
public ArrayList<GeometricObject> GeoObjects;
public ArrayList<LightObject> LightObjects;
public boolean Tracing;
public double AmbientLight;
public Tracer(Camera cam, int width, int height, BufferedImage image, Color backGroundColor, int startX, int startY, int endX, int endY, int rowCount, int colCount, ArrayList<GeometricObject> Geoobjects,ArrayList<LightObject> Lightobjects,double ambientLight) {
super();
Cam = cam;
Width = width;
Height = height;
Image = image;
BackGroundColor = backGroundColor;
StartX = startX;
StartY = startY;
EndX = endX;
EndY = endY;
RowCount = rowCount;
ColCount = colCount;
GeoObjects = Geoobjects;
LightObjects = Lightobjects;
if(ambientLight > 1){
AmbientLight = 1;
}else if(ambientLight < 0){
AmbientLight = 0;
}else{
AmbientLight = ambientLight;
}
}
public void TracePixelFast(int x, int y) {
Color color = new Color(BackGroundColor.r,BackGroundColor.g,BackGroundColor.b);
for(int o = 0;o < GeoObjects.size();o++){
GeometricObject GO = GeoObjects.get(o);
Ray r = new Ray(Cam.GetRayPos(Width, Height, x, y, 1, 1, RowCount, ColCount), Cam.GetRayDir(Width, Height, x, y, 1,1, RowCount, ColCount));
double hit = GO.hit(r);
if (hit != 0.0) {
color = Cal_Pixel(x,y);
Image.setRGB(x, y, color.toInt());
break;
}
}
}
public void TracePixelSmooth(int x, int y) {
Image.setRGB(x, y,Cal_Pixel(x,y).toInt());
}
public Color Cal_Pixel(int x,int y){
Color color = new Color(BackGroundColor);
Color colorh = new Color(BackGroundColor);
Color bgc = new Color(BackGroundColor);
int HIT = 0;
int MISS = 0;
for (int row = 0; row < RowCount; row++) {
for (int col = 0; col < ColCount; col++) {
double min = Double.MAX_VALUE;
for (int o = 0; o < GeoObjects.size(); o++) {
GeometricObject GO = GeoObjects.get(o);
Ray r = new Ray(Cam.GetRayPos(Width, Height, x, y, row, col, RowCount, ColCount),Cam.GetRayDir(Width, Height, x, y, row, col, RowCount, ColCount));
double hit = GO.hit(r);
if (hit != 0.0 && hit < min) {
min = hit;
colorh = ShadePixel(GO, r, hit);
HIT++;
} else {
double min2 = Double.MAX_VALUE;
for (int o2 = 0; o2 < GeoObjects.size(); o2++) {
if(o!=o2){
GeometricObject GO2 = GeoObjects.get(o2);
double hit2 = GO2.hit(r);
if (hit2 != 0.0 && hit2 < min2) {
min2 = hit2;
bgc = ShadePixel(GO2, r, hit2);
}
}
}
MISS++;
}
}
}
}
for(int h = 0;h < HIT;h++){
color.Add(colorh);
}
for(int m = 0;m < MISS;m++){
color.Add(bgc);
}
color.Divide(RowCount * ColCount);
return color;
}
public Color ShadePixel(GeometricObject GO,Ray ray,double t){
ArrayList<Color> PixelShade = new ArrayList<Color>();
Normal normal = GO.Cal_Normal(ray, t);
for(int l = 0;l < LightObjects.size();l++){
LightObject light = LightObjects.get(l);
Vector3D r_Dir = light.Pos.Sub(normal.Origin);
r_Dir.normalize();
Ray raytolight = new Ray(normal.Origin,r_Dir);
int WAS_HIT = 0;
for(int o = 0;o < GeoObjects.size();o++){
GeometricObject NGO = GeoObjects.get(o);
double hit = NGO.hit(raytolight);
if (hit != 0.0) {
WAS_HIT = 1;
}
}
if(WAS_HIT == 0){
double Dot = normal.Direction.Dot(r_Dir);
if(Dot < 0){
Dot = 0;
}
double Diffuse = 1 - AmbientLight;
Color color = new Color(GO.Color);
double Shade = AmbientLight + Diffuse*Dot;
color.Mul(Shade);
PixelShade.add(color);
}else{
Color color = new Color(GO.Color);
double Shade = AmbientLight;
color.Mul(Shade);
PixelShade.add(color);
}
}
Color Final = new Color();
for(int s = 0;s < PixelShade.size();s++){
Final.Add(PixelShade.get(s));
}
Final.Divide(PixelShade.size());
return Final;
}
public void TraceArea(boolean SmoothTracing) {
Tracing = true;
if(SmoothTracing){
for (int x = StartX; x < EndX; x++) {
for (int y = StartY; y < EndY; y++) {
TracePixelSmooth(x,y);
}
}
}else{
for (int x = StartX; x < EndX; x++) {
for (int y = StartY; y < EndY; y++) {
TracePixelFast(x,y);
}
}
}
}
}
And here is the code for the sphere.
public class Sphere extends GeometricObject{
public Vector3D Center;
public double Radius;
public Sphere(Vector3D Center,double Radius,Color Color){
this.Center = Center;
this.Radius = Radius;
this.Color = Color;
}
public double hit(Ray ray) {
double a = ray.Direction.Dot(ray.Direction);
double b = 2 * ray.Origin.Sub(Center).Dot(ray.Direction);
double c = ray.Origin.Sub(Center).Dot(ray.Origin.Sub(Center))-Radius*Radius;
double discreminant = b*b-4*a*c;
if(discreminant < 0.0f){
return 0.0;
}else{
double t = (-b - Math.sqrt(discreminant))/(2*a);
if(t > 10E-9){
return t;
}else{
return 0.0;
}
}
}
public Normal Cal_Normal(Ray ray,double t) {
Vector3D NPos = new Vector3D(ray.Origin.x + ray.Direction.x*t,ray.Origin.y + ray.Direction.y*t,ray.Origin.z + ray.Direction.z*t);
Vector3D NDir = NPos.Sub(Center).Div(Radius);
return new Normal(NPos,NDir);
}
}
I am sure the problem is in shadepixel() but I could be wrong.
I just found out that the more objects that I add the more rings there are:
1 object no rings.
2 objects 1 ring.
3 objects 2 rings.
If you need me to post more of my code.Just ask and I will.
When I get back from school I will post my color class and fix the color problem. I still do not understand why the more objects (spheres) I add, the more rings there are. Can anyone explain to me why this is happening?
Here is my Color code.
public class Color {
public float r,g,b;
public Color(){
r = 0.0f;
g = 0.0f;
b = 0.0f;
}
public Color(float fr,float fg,float fb){
r = fr;
g = fg;
b = fb;
}
public Color(Color color){
r = color.r;
g = color.g;
b = color.b;
}
public void Add(Color color){
r += color.r;
g += color.g;
b += color.b;
}
public void Divide(int scalar){
r /= scalar;
g /= scalar;
b /= scalar;
}
public void Mul(double mul){
r *= mul;
g *= mul;
b *= mul;
}
public int toInt(){
return (int) (r*255)<<16 | (int) (g*255)<<8 | (int) (b*255);
}
There are multiple issues with this code, but the direct reason for the rings is that color component values are overflowing 0-255 range. This in turn is caused by incorrect calculations in what I take to be an attempt at antialiasing in Cal_Pixel(), as well as by no control whatsoever of numeric range in ShadePixel().
Think about how you can visually debug this scene.
First are the normals correct? Display them as the colour to see.
Taking the range for each component [-1..1] to the range [0..255]:
r = 255*(n.x + 1)/2;
g = 255*(n.y + 1)/2;
b = 255*(n.z + 1)/2;
Once you think they look correct move on to the next stage and build it up stage by stage.
e.g. you might look at if your dot product is as expected (again [-1..1] because the vectors are supposedly normalised):
r = 255*(dot + 1)/2;
g = 255*(dot + 1)/2;
b = 255*(dot + 1)/2;

How can I make my image appear in a random position?

I have a chicken image that only moves whenever I press my arrow keys, the image always appear at the lower left corner when I start to run the program. My problem is that how can I make the image appear at the top or anywhere on the screen(except on the lower left) and the image still moves when I press the arrow keys . I'm not really sure but I think this problem is coming from my translate(). Is there something wrong with my calculation? Thanks for sharing your ideas...
Here's the code...
public class Chicken extends Sprite implements ImageObserver
{
private java.awt.Image fishImage;
private final Board board;
private double x;
private double y;
private final double chickenHeight = 1.6;
private final double chickenWidth = 1.8;
private double speed;
private boolean visible;
private double angle;
private double dx_m;
private double dy_m;
private boolean collision = false;
public Chicken(Board board, String name, double x, double y, double speed)
{
super(name);
this.board = board;
this.x = x;
this.y = y;
this.speed = convertToMeterPerSecond(speed);
visible = true;
URL iU = this.getClass().getResource("chicken.jpg");
ImageIcon icon = new ImageIcon(iU);
chickenImage = icon.getImage();
}
public Image getImage()
{
return chickenImage;
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
{
dx_m = -0.5;
}
if (key == KeyEvent.VK_RIGHT)
{
dx_m = 0.5;
}
if (key == KeyEvent.VK_UP)
{
dy_m = 0.5;
}
if (key == KeyEvent.VK_DOWN)
{
dy_m = -0.5;
}
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
{
dx_m = 0;
}
if (key == KeyEvent.VK_RIGHT)
{
dx_m = 0;
}
if (key == KeyEvent.VK_UP)
{
dy_m = 0;
}
if (key == KeyEvent.VK_DOWN)
{
dy_m = 0;
}
}
#Override
public void move(long dt)
{
double right_wall = board.x1_world;
double up_wall = board.y1_world;
double down_wall = 0.0;
double left_wall = 0.0;
x += dx_m;
y += dy_m;
if (x >= right_wall)
{
x = right_wall;
}
if (y > up_wall)
{
y = up_wall;
}
if (x <= left_wall)
{
x = left_wall;
}
if (y < down_wall)
{
y = down_wall;
}
}
#Override
public void render(Graphics2D g2d)
{
AffineTransform t = g2d.getTransform();
final double foot_position_y = chickenHeight;
final double foot_position_x = chickenWidth / 2;
double xx = board.convertToPixelX(x - foot_position_x);
double yy = board.convertToPixelY(y + foot_position_y);
g2d.translate(xx, yy);
// ratio for the actual size of the Image
double x_expected_pixels = chickenHeight * board.meter;
double y_expected_pixels = chickenWidth * board.meter;
double w = ((ToolkitImage) chickenImage).getWidth();
double h = ((ToolkitImage) chickenImage).getHeight();
double x_s = x_expected_pixels / w;
double y_s = y_expected_pixels / h;
g2d.scale(x_s, y_s);
g2d.drawImage(getImage(), (int) x, (int) y, this);
g2d.setTransform(t);
}
#Override
public void moveAt(double distance_x, double distance_y)
{
this.x = (int) distance_x;
this.y = (int) distance_y;
}
public void setAngle(double angle)
{
this.angle = angle;
}
#Override
public RectangleX getBounds()
{
return new RectangleX(x, y, chickenWidth, chickenHeight);
}
#Override
public double getWidth()
{
return WIDTH;
}
#Override
public double getHeight()
{
return HEIGHT;
}
#Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
{
return true;
}
}
this is my chicken class
public double meter;
int y1_pixel;
y1_pixel = getHeight();
public int convertToPixelX(double distance)
{
return (int) (distance * meter);
}
public int convertToPixelY(double y_world)
{
return (int) (y1_pixel - (y_world * meter));
}
this is coming from my board class.
Your render method is using the x and y coordinates of the class to determine where to draw the Chicken each time. A simple solution to your problem is to use random values for x and y when you create a Chicken instance.
An alternate solution would be to create another constructor that do not take values for x or y and instead sets them to be default values anywhere between 0 and board.x1_world or board.y1_world, depending on the variable.
public Chicken(Board board, String name, double speed)
{
this( board, name,
(int)( Math.random() * ( board.x1_world - chickenWidth ) ),
(int)( Math.random() * ( board.y1_world - chickenHeight ) ),
speed );
}

Categories

Resources