Could someone please tell me why my code does not work Properly?
I am trying to make the colour change when I move over it but its just not working.
I'm using the intersects method.
package com.dilkiel.game;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Screen extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private Thread thread;
public int tickCount = 0;
public boolean running = false;
public int xPlayerOffset = 100;
public int yPlayerOffset = 100;
public int WIDTH = 1280;
public int HEIGHT = 720;
public InputHandler input = new InputHandler(this);
public Screen() {
setFocusable(true);
setMaximumSize(new Dimension(WIDTH, HEIGHT));
setMinimumSize(new Dimension(WIDTH, HEIGHT));
setPreferredSize(new Dimension(WIDTH, HEIGHT));
start();
}
public void tick() {
tickCount++;
if (input.up.isPressed()) {
yPlayerOffset -= 5;
}
if (input.down.isPressed()) {
yPlayerOffset += 5;
}
if (input.left.isPressed()) {
xPlayerOffset -= 5;
}
if (input.right.isPressed()) {
xPlayerOffset += 5;
}
}
public synchronized void start() {
running = true;
thread = new Thread(this, "Game Loop");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Image frontView = new ImageIcon("res/frontView.png").getImage();
Rectangle player = new Rectangle(xPlayerOffset, yPlayerOffset + 40, 40, 40);
Rectangle box = new Rectangle(250, 250, 80, 80);
public void paint(Graphics g) {
g.setColor(Color.CYAN);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.drawImage(frontView, xPlayerOffset, yPlayerOffset, this);
g.setColor(Color.BLACK);
if (player.intersects(box)) {
//i want this to work can you please show me how. Thanks
g.setColor(Color.GREEN);
}
g.fillRect(xPlayerOffset, yPlayerOffset + 40, 40, 40);
g.fillRect(250, 250, 80, 80);
g.dispose();
}
public void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1000000000D / 60D;
int ticks = 0;
int frames = 0;
long lastTimer = System.currentTimeMillis();
double delta = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / nsPerTick;
lastTime = now;
boolean shouldRender = false;
while (delta >= 1) {
ticks++;
tick();
delta -= 1;
shouldRender = true;
}
/*
* try { Thread.sleep(2); } catch (InterruptedException e) {
* e.printStackTrace(); }
*/
if (shouldRender) {
frames++;
repaint();
}
if (System.currentTimeMillis() - lastTimer >= 1000) {
lastTimer += 1000;
System.out.println(ticks + ", " + frames);
frames = 0;
ticks = 0;
}
}
}
}