My clickgui don't work... When i click on it - java

So, i coding a minecraft client from quickdaffy tutorial (click gui is in 7ep)..
Another So, if i click on "testMod" button, nothing happends
Link for this tutorial: www.youtube.com/watch?v=SR_NAVTTD5o&t
This is the code for click gui (without imports):
package moonlight.ui.clickgui;
public class ClickGUI extends GuiScreen {
ArrayList<ModButton> modButtons = new ArrayList();
#Override
public void initGui() {
super.initGui();
this.modButtons.add(new ModButton(210, 60, 240, 100, Moonlight.INSTANCE.hudManager.testMod));
}
#Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
ScaledResolution sr = new ScaledResolution(mc);
super.drawScreen(mouseX, mouseY, partialTicks);
Gui.drawRect(200, 50, sr.getScaledWidth(), sr.getScaledHeight(), 0x20000000);
for(ModButton m : modButtons) {
m.draw();
}
}
#Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
super.mouseClicked(mouseX, mouseY, mouseButton);
}
}
And this is for gui button (without imports):
package moonlight.ui.clickgui.comp;
public class ModButton {
public int x, y, w, h;
public HudMod m;
public ModButton(int x, int y, int w, int h, HudMod m) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.m = m;
}
public void draw() {
Gui.drawRect(y, x, h, w, 0x20000000);
Minecraft.getMinecraft().fontRendererObj.drawString(m.name, x + 2, y + 2, getColor());
}
private int getColor() {
if(m.isEnabled()) {
return new Color(0,255,0,255).getRGB();
} else {
return new Color(255,0,0,255).getRGB();
}
}
public void ocClick(int mouseX, int mouseY, int button) {
if (mouseX >= x && mouseX <= x + w && mouseY >= y && mouseY <= y + h) {
m.toggle();
System.out.println("HELLO");
}
}
}
Rly, please help

Related

Error in setting my character in the right color pixel in java

I am having some issues trying to set my character to spawn in the right color spot in my map sheet in java.
In the vídeos that I am watching to learn this I have every single line code identical to the vídeo but yet my character instead of spawning in the right spot is spawning in the up middle corner of the screen.
I'm using those code lines to make him and all Tiles and Entities spawn in the right spot :
public class World {
private Tile[] tiles;
public static int WIDTH,HEIGHT;
public World(String path) {
try {
BufferedImage map = ImageIO.read(getClass().getResource(path));
int[] pixels = new int[map.getWidth() * map.getHeight()];
WIDTH = map.getWidth();
HEIGHT = map.getHeight();
tiles = new Tile[map.getWidth() * map.getHeight()];
map.getRGB(0, 0, map.getWidth(), map.getHeight(), pixels, 0, map.getWidth());
for(int xx = 0; xx < map.getWidth(); xx++) {
for(int yy = 0; yy < map.getHeight(); yy++) {
int pixelAtual = pixels[xx + (yy*map.getWidth())];
tiles[xx + (yy * WIDTH)] = new FloorTile(xx*16,yy*16, Tile.TILE_FLOOR);
if(pixelAtual == 0xFF000000) {
//FLOOR
tiles[xx + (yy * WIDTH)] = new FloorTile(xx*16,yy*16, Tile.TILE_FLOOR);
}else if(pixelAtual == 0xFFFFFFFF){
//PAREDE
tiles[xx + (yy * WIDTH)] = new FloorTile(xx*16,yy*16, Tile.TILE_WALL);
}else if(pixelAtual == 0xFF0026FF) {
//Player
Game.player.setX(xx*16);
Game.player.setY(yy*16);
}else if(pixelAtual == 0xFFFF0000){
//Enemy
}else if(pixelAtual == 0xFFFF00DC) {
//WEAPON
}else if(pixelAtual == 0xFFFF7F7F) {
//LIFEPACK
}else if(pixelAtual == 0xFFFFD800) {
//BULLET
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void render(Graphics g) {
for(int xx = 0; xx < WIDTH; xx++) {
for(int yy = 0; yy < HEIGHT; yy++) {
Tile tile = tiles[xx + (yy*WIDTH)];
tile.render(g);
}
}
}
}
But when I use these two code lines that are from my Entity Class that are suposed to make my character spawn in the right place it doesn't work at all!
Game.player.setX(xx16);
Game.player.setY(yy16);
Here's my Entity Class for you to see if i did something wrong, and again, i did everything exactely like int the vídeo an in the vídeo it worked.
public class Entity {
public static BufferedImage LIFEPACK_EN = Game.spritesheet.getSprite(78, 0, 16, 16);
public static BufferedImage WEAPON_EN = Game.spritesheet.getSprite(96, 0, 16, 16);
public static BufferedImage BULLET_EN = Game.spritesheet.getSprite(78, 16, 16, 16);
public static BufferedImage ENEMY_EN = Game.spritesheet.getSprite(96, 16, 16, 16);
protected double x;
protected double y;
protected int width;
protected int height;
private BufferedImage sprite;
public Entity(int x, int y, int width, int height, BufferedImage sprite) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.sprite = sprite;
}
public void setX(int newX) {
this.x = newX;
}
public void setY(int newY) {
this.x = newY;
}
public int getX() {
return (int)this.x;
}
public int getY() {
return (int)this.y;
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
public void update() {
}
public void render(Graphics g) {
g.drawImage(sprite, this.getX(), this.getY(), null);
}
}
I saw where I was wrong.
public void setY(int newY) {
this.x = newY;
In this line code here, it's suposed to be this.y and I thought that I did that, but I couldn't see.

Detecting Collision between two filled Rectangles

I'm trying to make it print out "Game over" when the Green Square(Cuboid) runs over/into the blue(CuboidKiller) one.
GAME class:
package plugin.dev.wristz;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
public class Game extends JFrame {
private static final long serialVersionUID = 294623570092988970L;
public static ArrayList<CuboidKiller> killers;
public static int h = 1024, w = 768;
public static Game game;
public static Graphics graphics, g2;
public static Image image;
public static Cuboid cuboid;
public Game(String title) {
setTitle(title);
setSize(1024, 768);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setVisible(true);
setLocationRelativeTo(null);
addKeyListener(new KeyHandler(cuboid));
g2 = getGraphics();
paint(g2);
}
public static void main(String[] args) {
cuboid = new Cuboid();
Thread cubi = new Thread(cuboid);
cubi.start();
killers = new ArrayList<CuboidKiller>();
CuboidKiller a = new CuboidKiller(new Random().nextInt(h), new Random().nextInt(w), new Random().nextInt(50) + 20);
killers.add(a);
game = new Game("Killer Cuboids");
}
#Override
public void paint(Graphics g) {
image = createImage(getWidth(), getHeight());
graphics = image.getGraphics();
paintComponent(graphics);
g.drawImage(image, 0, 0, this);
}
public void paintComponent(Graphics g) {
checkGameOver();
cuboid.draw(g);
for (CuboidKiller killer : killers)
killer.draw(g);
repaint();
}
public void checkGameOver() {
for (CuboidKiller killer : killers)
if (killer.isTouching(cuboid))
System.out.println("Game over!");
}
public int getH() {
return h;
}
public void setH(int wh) {
h = wh;
}
public int getW() {
return w;
}
public void setW(int ww) {
w = ww;
}
}
Cuboid class:
package plugin.dev.wristz;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
#SuppressWarnings("static-access")
public class Cuboid implements Runnable {
private int x, y, xDirection, zDirection;
public Cuboid() {
this.x = 799;
this.y = 755;
}
public void draw(Graphics g) {
g.setColor(Color.GREEN);
g.fillRect(x, y, 25, 25);
}
public void move() {
x += xDirection;
y += zDirection;
if (x <= 10)
x = 0 + 10;
if (y <= 35)
y = 0 + 35;
if (x >= 1024 - 35)
x = 1024 - 35;
if (y >= 768 - 35)
y = 768 - 35;
}
public void keyPressed(KeyEvent ev) {
int keyCode = ev.getKeyCode();
if (keyCode == ev.VK_LEFT) {
setXDirection(-5);
}
if (keyCode == ev.VK_RIGHT) {
setXDirection(5);
}
if (keyCode == ev.VK_UP) {
setZDirection(-5);
}
if (keyCode == ev.VK_DOWN) {
setZDirection(5);
}
}
public void keyReleased(KeyEvent ev) {
int keyCode = ev.getKeyCode();
if (keyCode == ev.VK_LEFT) {
setXDirection(0);
}
if (keyCode == ev.VK_RIGHT) {
setXDirection(0);
}
if (keyCode == ev.VK_UP) {
setZDirection(0);
}
if (keyCode == ev.VK_DOWN) {
setZDirection(0);
}
}
#Override
public void run() {
try {
while (true) {
move();
Thread.sleep(5);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getXDirection() {
return xDirection;
}
public void setXDirection(int xDirection) {
this.xDirection = xDirection;
}
public int getZ() {
return y;
}
public void setZ(int z) {
this.y = z;
}
public int getZDirection() {
return zDirection;
}
public void setZDirection(int zDirection) {
this.zDirection = zDirection;
}
}
Cuboid Killer:
package plugin.dev.wristz;
import java.awt.Color;
import java.awt.Graphics;
import java.util.HashMap;
public class CuboidKiller {
private int x, y, radius;
private HashMap<Integer, Integer> points;
public CuboidKiller(int x, int y, int radius) {
this.points = new HashMap<Integer, Integer>();
setPoints();
this.x = x;
this.y = y;
this.radius = radius;
}
public void draw(Graphics g) {
g.setColor(Color.blue);
g.fillRect(x, y, radius, radius);
}
public void setPoints() {
this.points.put(x, y);
this.points.put(x + radius, y);
this.points.put(x + radius, y - radius);
this.points.put(x, y - radius);
}
public boolean isTouching(Cuboid cuboid) {
boolean result = true;
//int a = cuboid.getX(), b = cuboid.getZ();
result = true;
return result;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public HashMap<Integer, Integer> getPoints() {
return points;
}
public void setPoints(HashMap<Integer, Integer> points) {
this.points = points;
}
}
Well, there are two approaches. Either you write it yourself, or you just use what Java 8 provides.
This guy has a very nice explanation on how to detect collision between two rectangles: Java check if two rectangles overlap at any point
But if I were the one writing it, I would just have both classes contain a Rectangle object (http://docs.oracle.com/javase/8/docs/api/java/awt/Rectangle.html), and just call the intersects() function provided by Rectangle. :-)

GUI thread move() method misbehaving

EDIT
: it seems that in my move() method, java has to skip one of the 2 if statements
Keeping it simple. I'm trying to make a GUI in java that models the following class Truck behavior: the blue squares are supposed to run up their diagonales, which they do. But when they are supposed to bounce back once they reach the edge point of the square they just fly away. I've placed a condition to prevent this, but it never passes. I'll upload GUI and Drawable, but I don't think they are needed.
Class Truck:
package construction_site;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.plaf.ButtonUI;
public class Truck extends Thread implements Drawable {
private boolean isFull = false;
private int x, y;
private int capacity;
private Panel panel;
static int r = 20;
private int dx, dy;
private Site site;
private Building building;
public Truck(int x, int y, Panel panel, Building building, Site site) {
this.x = x;
this.y = y;
this.building = building;
this.panel = panel;
this.site = site;
this.start();
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
#Override
public void run() {
super.run();
while (true) {
move();
panel.repaint();
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setDirection(int i) {
if (i == 0) {
dx = -1;
dy = -1;
}
if (i == 1) {
dx = 1;
dy = -1;
}
if (i == 2) {
dx = -1;
dy = 1;
}
if (i == 3) {
dx = 1;
dy = 1;
}
}
private void move() {
if (site.truckOnSite(x, y)) {
site.loadTruck(this);
dx *= -1;
dy *= -1;
}
if (building.containsTruck(this)) {
building.unloadTruck(this);
dx *= -1;
dy *= -1;
}
x += dx;
y += dy;
}
public int getDx() {
return dx;
}
public void setFull(boolean isFull) {
this.isFull = isFull;
}
#Override
public void draw(Graphics g) {
g.setColor(Color.BLUE);
if (isFull)
g.fillRect(x - 10, y - 10, r, r);
else
g.drawRect(x - 10, y - 10, r, r);
}
}
Class Panel:
package construction_site;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JPanel;
public class Panel extends JPanel {
private ArrayList<Drawable> drawables = new ArrayList<>();
private Site site;
private Building[] buildings = new Building[4];
private Truck[] trucks = new Truck[4];
private Van[] vans = new Van[4];
public Panel(int w, int h) {
setPreferredSize(new Dimension(w, h));
site = new Site(100, 75, 500, 500, this);
drawables.add(site);
buildings[0] = new Building(100, 75, this);
buildings[1] = new Building(100 + 500, 75, this);
buildings[2] = new Building(100, 75 + 500, this);
buildings[3] = new Building(100 + 500, 75 + 500, this);
for (Building b : buildings)
drawables.add(b);
trucks[0] = new Truck(100 + 250, 75 + 250, this, buildings[0], site);
trucks[1] = new Truck(100 + 250, 75 + 250, this, buildings[1], site);
trucks[2] = new Truck(100 + 250, 75 + 250, this, buildings[2], site);
trucks[3] = new Truck(100 + 250, 75 + 250, this, buildings[3], site);
for (int i = 0; i < 4; i++)
trucks[i].setDirection(i);
for (Truck t : trucks)
drawables.add(t);
}
#Override
public void paint(Graphics g) {
super.paint(g);
for (Drawable d : drawables)
d.draw(g);
g.setColor(Color.GREEN);
for (int i = 1; i <= 3; i++)
g.drawLine(buildings[0].getX(), buildings[0].getY(), buildings[i].getX(), buildings[i].getY());
g.drawLine(buildings[1].getX(), buildings[1].getY(), buildings[2].getX(), buildings[2].getY());
}
}
Class Building:
package construction_site;
import java.awt.Color;
import java.awt.Graphics;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Building extends Thread implements Drawable {
private Panel panel;
private boolean done = false;
private int x, y;
static int w = 100;
static int h = 100;
private ReentrantLock lock = new ReentrantLock();
private Condition insufficientMaterial = lock.newCondition();
private Condition insufficientMisc = lock.newCondition();
private Condition sufficient = lock.newCondition();
private int material = 0;
private int misc = 0;
private int spent = 0;
public Building(int x, int y, Panel panel) {
this.x = x;
this.y = y;
this.panel = panel;
this.start();
}
#Override
public void run() {
super.run();
lock.lock();
while(material < 100 )
try {
insufficientMaterial.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
spent += 150;
misc -= 50;
material -= 100;
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void unloadVan(Van v) {
lock.lock();
System.out.println("Truck got in");
if (material >= 100 && misc >=50) {
}
misc += 50;
v.setCapacity(0);
insufficientMisc.signalAll();
lock.unlock();
}
public void unloadTruck(Truck t) {
lock.lock();
material += 10000;
t.setCapacity(0);
t.setFull(false);
insufficientMaterial.signalAll();
lock.unlock();
}
public void setMaterial(int material) {
this.material = material;
}
public void setMisc(int misc) {
this.misc = misc;
}
public boolean containsVan(int x2, int y2) {
return ( Math.sqrt((x - x2)*(x - x2) + (y - y2)*(y - y2)) <= h/2 );
}
public boolean containsTruck(Truck t) {
return (x == t.getX() && y == t.getY());
}
public int getX() {
return x;
}
public int getY() {
return y;
}
#Override
public void draw(Graphics g) {
g.setColor(Color.BLACK);
g.drawRect(x - 50, y - 50, 100, 100);
}
}
Class Site:
package construction_site;
import java.awt.Color;
import java.awt.Graphics;
public class Site implements Drawable {
private int x, y, w, h;
private Panel panel;
public Site(int x, int y, int w, int h, Panel panel) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.panel = panel;
}
public boolean contains(int x2, int y2) {
return (x == x2 && y == 2);
}
public boolean truckOnSite(int x2, int y2) {
return ( x2 == x + w / 2 && y2 == y + h / 2);
}
public boolean vanOnSite(int x2, int y2) {
return ( (x2 == x && y2 == y + h / 2) || (x2 == x + w && y2 == y + h / 2) );
}
public void loadVan(Van v) {
v.setCapacity(5000);
}
public void loadTruck(Truck t) {
t.setCapacity(10000);
t.setFull(true);
}
#Override
public void draw(Graphics g) {
g.setColor(Color.GRAY);
g.fillRect(x, y, w, h);
}
}
As it turned out much later, it doesn't seem truncation errors were the problem at hand. It was a mistake at setting the trucks' starting point and the condition that decides when they're supposed to turn the other way. What looked like the truck bouncing off, was actually the oppsoite truck from the same diagonal passing through. A simple change in direction of my Truck's move() method did the trick.
public void setDirection(int i) {
if (i == 0) {
dx = -1;
dy = -1;
}
if (i == 1) {
dx = 1;
dy = -1;
}
if (i == 2) {
dx = -1;
dy = 1;
}
if (i == 3) {
dx = 1;
dy = 1;
}
}

How to stop my bubbles animation from flickering? Tried nearly everything

I'm in despair, because my animation isn't as smooth as I expected. So I know, there is a lot of stuff around this problem, but mine is different in that way, that I know the common problems and I think, I'm doing it right. So firstly, this is my code:
Game.java
import de.lwerner.collisions.CircleCollision;
import de.lwerner.collisions.math.Vector2D;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
public class Game extends JPanel implements ActionListener {
private static final Color BACKGROUND_COLOR = new Color(0, 0, 25);
private static final Color TEXT_COLOR = Color.WHITE;
private static final int TARGET_FPS = 60;
private javax.swing.Timer swingTimer;
private JFrame window;
private Timer timer;
private Timer fpsTimer;
private int counter;
private long[] diffs;
private int fps;
private LinkedList<Circle> circles;
private LinkedList<Sprite> sprites;
public Game() {
timer = new Timer();
fpsTimer = new Timer(System.currentTimeMillis());
diffs = new long[TARGET_FPS];
circles = new LinkedList<>();
circles.add(new Circle(100, 100, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(250, 250, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(400, 400, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(550, 550, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(700, 700, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(100, 700, 50, -300, 300, Color.WHITE));
// circles.add(new Circle(250, 550, 50, 300, -300, Color.WHITE));
// circles.add(new Circle(550, 250, 50, 300, -300, Color.WHITE));
// circles.add(new Circle(700, 100, 50, -300, 300, Color.WHITE));
sprites = new LinkedList<>();
sprites.addAll(circles);
window = new JFrame("Game");
window.setContentPane(this);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
window.setUndecorated(true);
window.setResizable(false);
window.validate();
window.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
stop();
}
});
window.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
stop();
}
});
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(window);
}
#Override
protected void paintComponent(Graphics g) {
g.setColor(BACKGROUND_COLOR);
g.fillRect(0, 0, getWidth(), getHeight());
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (Sprite s: sprites) {
s.render(g);
}
g.setColor(TEXT_COLOR);
g.drawString(fps + " FPS", 10, 20);
diffs[counter % TARGET_FPS] = fpsTimer.tick();
if (++counter % TARGET_FPS == 0) {
int sum = 0;
for (long diff: diffs) {
sum += diff;
}
fps = 1000 / (sum / TARGET_FPS);
}
}
private void step() {
long tick = timer.tick();
for (Sprite s: sprites) {
s.update(tick);
}
repaint();
checkCollisions();
}
private void checkCollisions() {
for (Sprite s1: sprites) {
BoundingBox bb = s1.getBoundingBox();
int offset = 0;
if (s1 instanceof Circle) {
offset = ((Circle) s1).getRadius();
}
if (bb.getLeft() < 0 || bb.getRight() >= getWidth()) {
s1.setVelX(-s1.getVelX());
if (bb.getLeft() < 0) {
s1.setX(0 + offset);
} else {
s1.setX(getWidth() - 1 - offset);
}
}
if (bb.getTop() < 0 || bb.getBottom() >= getHeight()) {
s1.setVelY(-s1.getVelY());
if (bb.getTop() < 0) {
s1.setY(0 + offset);
} else {
s1.setY(getHeight() - 1 - offset);
}
}
}
// Set<Set<Circle>> collidingPairs = new HashSet<>();
// for (Circle c1: circles) {
// for (Circle c2: circles) {
// if (c1 == c2) {
// continue;
// } else {
// if (c1.intersects(c2)) {
// Set<Circle> pair = new HashSet<>(Arrays.asList(c1, c2));
// if (!collidingPairs.contains(pair)) {
// collidingPairs.add(pair);
// de.lwerner.collisions.Circle cc1 = new de.lwerner.collisions.Circle(c1.getX(), c1.getY(), c1.getRadius(), new Vector2D(c1.getVelX(), c1.getVelY()));
// de.lwerner.collisions.Circle cc2 = new de.lwerner.collisions.Circle(c2.getX(), c2.getY(), c2.getRadius(), new Vector2D(c2.getVelX(), c2.getVelY()));
// CircleCollision collision = new CircleCollision(cc1, cc2);
// collision.resolveCollision();
// Vector2D v1New = cc1.getV();
// Vector2D v2New = cc2.getV();
// c1.setVelX((int) v1New.getX());
// c1.setVelY((int) v1New.getY());
// c2.setVelX((int) v2New.getX());
// c2.setVelY((int) v2New.getY());
// }
// }
// }
// }
// }
}
private void stop() {
if (swingTimer.isRunning()) {
swingTimer.stop();
window.dispose();
}
}
public void start() {
swingTimer = new javax.swing.Timer(1000 / TARGET_FPS, this);
swingTimer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
step();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Game().start());
}
}
Sprite.java
import java.awt.*;
public abstract class Sprite {
protected double x;
protected double y;
protected int width;
protected int height;
protected int velX;
protected int velY;
public Sprite(int x, int y, int width, int height) {
this(x, y, width, height, 0, 0);
}
public Sprite(int x, int y, int width, int height, int velX, int velY) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.velX = velX;
this.velY = velY;
}
public int getX() {
return (int)Math.round(x);
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return (int)Math.round(y);
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getVelX() {
return velX;
}
public void setVelX(int velX) {
this.velX = velX;
}
public int getVelY() {
return velY;
}
public void setVelY(int velY) {
this.velY = velY;
}
public void update(long tick) {
x += tick * velX / 1000.0;
y += tick * velY / 1000.0;
}
public BoundingBox getBoundingBox() {
return new BoundingBox(getY(), getX() + width, getY() + height, getX());
}
public boolean intersects(Sprite other) {
return getBoundingBox().intersects(other.getBoundingBox());
}
public abstract void render(Graphics g);
}
Circle.java
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class Circle extends Sprite {
private Color color;
private BufferedImage image;
public Circle(int x, int y, int r, Color c) {
super(x, y, r * 2, r * 2);
color = c;
// try {
// loadImage();
// } catch (Exception e) {
//
// }
}
public Circle(int x, int y, int r, int velX, int velY, Color c) {
super(x, y, r * 2, r * 2, velX, velY);
color = c;
// try {
// loadImage();
// } catch (Exception e) {
//
// }
}
private void loadImage() throws IOException {
image = ImageIO.read(getClass().getResource("/bubble.png"));
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public int getRadius() {
return width / 2;
}
public boolean intersects(Circle other) {
int dx = Math.abs(getX() - other.getX());
int dy = Math.abs(getY() - other.getY());
int r1 = getRadius();
int r2 = other.getRadius();
return dx * dx + dy * dy < (r1 + r2) * (r1 + r2);
}
#Override
public BoundingBox getBoundingBox() {
return new BoundingBox(getY() - getRadius(), getX() + getRadius(), getY() + getRadius(), getX() - getRadius());
}
#Override
public void render(Graphics g) {
if (image == null) {
g.setColor(color);
g.fillOval(getX() - getRadius(), getY() - getRadius(), width, height);
} else {
g.drawImage(image, getX() - getRadius(), getY() - getRadius(), null);
}
}
}
Timer.java
public class Timer {
private long lastTime;
public Timer() {
this(0L);
}
public Timer(long initialTime) {
lastTime = initialTime;
}
public long tick() {
if (lastTime == 0) {
lastTime = System.currentTimeMillis();
return 0;
}
long current = System.currentTimeMillis();
long diff = current - lastTime;
lastTime = current;
return diff;
}
}
BoundingBox.java
import java.awt.*;
public class BoundingBox {
private int top;
private int right;
private int bottom;
private int left;
public BoundingBox(int top, int right, int bottom, int left) {
this.top = top;
this.right = right;
this.bottom = bottom;
this.left = left;
}
public int getTop() {
return top;
}
public int getRight() {
return right;
}
public int getBottom() {
return bottom;
}
public int getLeft() {
return left;
}
public Rectangle getRectangle() {
return new Rectangle(left, top, right - left, bottom - top);
}
public boolean intersects(BoundingBox other) {
return getRectangle().intersects(other.getRectangle());
}
#Override
public String toString() {
return "BoundingBox{" +
"top=" + top +
", right=" + right +
", bottom=" + bottom +
", left=" + left +
'}';
}
}
So I don't know, what I'm doing wrong. Common problems such as calling paint(), using not-doublebuffered components, using wrong methods for periodically run code and so on aren't present, yet it's flickering. The FPS are constant.
So, please help me! I'd be very glad to come over this...
Thanks!

Button Doesn't Coordinate As Supposed

So I got two buttons on this state Click here to see the screenshot
And what is actually happening is that my second button "Start", doesn't work with this values:
backButton.renderImage(g, CONTAINER_CENTER_X - backButton.getWidth() - 10, CONTAINER_MAX_Y - backButton.getHeight() - 30);
startButton.renderImage(g, CONTAINER_CENTER_X + 10, CONTAINER_MAX_Y - startButton.getHeight() - 30);
Here is output of button coordinates and values I set for x and y:
BACK BUTTON: [x=245, y= 535, width= 145, height=35] / CURRENT X: 245 /
CURRENT Y: 535 START BUTTON: [x=410, y= 535, width= 0, height=35] /
CURRENT X: 410 / CURRENT Y: 535
Then I found out, that by adding and subtracting button.getWidth(), I get the button to work
backButton.renderImage(g, CONTAINER_CENTER_X - backButton.getWidth() - 10, CONTAINER_MAX_Y - backButton.getHeight() - 30);
startButton.renderImage(g, CONTAINER_CENTER_X + startButton.getWidth() - startButton.getWidth() + 10, CONTAINER_MAX_Y - startButton.getHeight() - 30);
which is pretty strange, and is very ugly... :D
Here is output of button coordinates and values I set for x and y:
BACK BUTTON: [x=245, y= 535, width= 145, height=35] / CURRENT X: 245 /
CURRENT Y: 535
START BUTTON: [x=410, y= 535, width= 145, height=35] / CURRENT X: 410 / CURRENT Y: 535
So, check this state code and button class, and tell me what do you think?
ThisState
package poker;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.state.transition.FadeInTransition;
import org.newdawn.slick.state.transition.FadeOutTransition;
import poker.gui.PButton;
import poker.gui.UIConstants;
import static poker.gui.UIConstants.CONTAINER_CENTER_X;
import static poker.gui.UIConstants.CONTAINER_MAX_Y;
import poker.util.RandomUtility;
public class SetupScreenState extends BasicGameState implements UIConstants, StatePanelInterface {
public static final int ID = 2;
private Image titleImage;
private PButton backButton;
private PButton startButton;
public SetupScreenState() {
}
#Override
public int getID() {
return ID;
}
#Override
public void init(GameContainer container, StateBasedGame game) throws SlickException {
titleImage = new Image("res/gui/title_setup.png");
backButton = new PButton("res/gui/button_back.png", "res/gui/button_back_hover.png");
startButton = new PButton("res/gui/button_start.png", "res/gui/button_start_hover.png");
}
#Override
public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
RandomUtility.bgTheme(container, g);
renderTopPanel(container, game, g);
renderCenterPanel(container, game, g);
renderBottomPanel(container, game, g);
}
#Override
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
Input input = container.getInput();
int mx = input.getMouseX();
int my = input.getMouseY();
if (backButton.contains(mx, my)) {
if (backButton.isButtonPressed(input)) {
game.enterState(StartScreenState.ID, new FadeOutTransition(), new FadeInTransition());
}
} else if (startButton.contains(mx, my)) {
if (startButton.isButtonPressed(input)) {
game.enterState(PlayScreenState.ID, new FadeOutTransition(), new FadeInTransition());
}
}
}
#Override
public void renderTopPanel(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
g.drawImage(titleImage, 50, 50);
}
#Override
public void renderCenterPanel(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
}
#Override
public void renderBottomPanel(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
backButton.renderImage(g, CONTAINER_CENTER_X - backButton.getWidth() - 10, CONTAINER_MAX_Y - backButton.getHeight() - 30);
startButton.renderImage(g, CONTAINER_CENTER_X + startButton.getWidth() - startButton.getWidth() + 10, CONTAINER_MAX_Y - startButton.getHeight() - 30);
}
}
BUTTON CLASS
package poker.gui;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
public class PButton {
private int x;
private int y;
private int width;
private int height;
private Image image;
private String classicImage;
private String hoverImage;
public PButton() {
}
public PButton(String classicImage, String hoverImage) throws SlickException {
this.classicImage = classicImage;
this.hoverImage = hoverImage;
image = new Image(classicImage);
}
public PButton(String classicImage, String hoverImage, int x, int y) throws SlickException {
this.classicImage = classicImage;
this.hoverImage = hoverImage;
this.x = x;
this.y = y;
image = new Image(classicImage);
}
public void renderImage(Graphics g) {
g.drawImage(image, x, y);
}
public void renderImage(Graphics g, int x, int y) throws SlickException {
this.x = x;
this.y = y;
g.drawImage(image, x, y);
}
public boolean contains(int x, int y) throws SlickException {
int minX = this.x;
int minY = this.y;
int maxX = this.x + this.width;
int maxY = this.y + this.height;
if ((x > minX && x < maxX) && (y > minY && y < maxY)) {
if (hoverImage != null) {
image = new Image(hoverImage);
}
return true;
}
image = new Image(classicImage);
return false;
}
public boolean isButtonPressed(Input input) throws SlickException {
return input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void setWidth(int width) {
this.width = width;
}
public int getWidth() {
return width = image.getWidth();
}
public void setHeight(int height) {
this.height = height;
}
public int getHeight() {
return height = image.getHeight();
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
#Override
public String toString() {
return "[x=" + x + ", y= " + y + ", width= " + width + ", height=" + height + "]";
}
}
Your problem is that you don't initialize the width fields properly.
In contains(), you use this.width, but it has not been initialized (or precisely it has been default initialized to 0 because it is an instance variable).
When you call getWidth(), width initializes because return width = image.getWidth(); assigns this.width = image.getWidth(), which explains why you have to call getWidth() to get your button to work.
Make sure you initialize your button fields properly. For example, when you create the button (i.e. in the constructor), you should set width to image.getWidth()

Categories

Resources