package game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
public class Player {
private Rectangle playerRec;
float x, y;
PlayerJLabel playerJLabel;
int worldX = 800;
int worldY = 600;
int targetX, targetY;
public Player(int posX, int posY, int size){
playerRec = new Rectangle(posX, posY, size, size);
x = posX;
y = posY;
playerJLabel = new PlayerJLabel();
playerJLabel.setBounds(0, 0, 800, 600);
Game.screen.add(playerJLabel);
}
public void update(float timeSinceLastFrame){
if (Mouse.isMouse(MouseEvent.BUTTON3)) {
targetX = Mouse.getX();
targetY = Mouse.getY();
}
if ((targetX != 0 && targetX != x) && (targetY != 0 && targetY != y)) {
float dx = (float) (targetX-x);
float dy = (float) (targetY-y);
// normalize
float length = (float) Math.sqrt(dx*dx+dy*dy);
dx/=length;
dy/=length;
// add speed
x = dx * timeSinceLastFrame * 300;
y = dy * timeSinceLastFrame * 300;
// Move the player
playerRec.x = (int) x;
playerRec.y = (int) y;
}
}
private Rectangle getRec(){
return playerRec;
}
public class PlayerJLabel extends JLabel{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(getRec().x, getRec().y, getRec().width, getRec().height);
}
}
}
Edit: I have a GameState method which calls the player update() method and a repaint() method which repains the whole scene.
GameState update method:
@Override
public void update(float lastFrame) {
player.update(lastFrame);
}
Game repaint method:
public void repaint() {
screen.repaint();
}
Main class
package game;
public class Main {
public static void main(String[] args) {
Game game = new Game("Mein erstes Spiel", 800, 600);
long lastFrame = System.nanoTime();
while(game.isRunning()) {
long thisFrame = System.nanoTime();
float timeSinceLastFrame = ((float)(thisFrame-lastFrame))/100000f;
lastFrame=thisFrame;
game.nextState();
game.update(timeSinceLastFrame);
game.repaint();
}
}
}