I am still new to java and I've been trying to make a SpaceInvaders copy in Java's native graphics. I've finished the basic mechanics, however the game slows down significantly when the player or aliens shoot a bullet. I have tried to find out what was causing the game to slow down, but was unable to.
public class Board extends JPanel implements KeyListener,ActionListener{
Ship ship;
Alien[] row1 = new Alien[10];
Alien[] row2 = new Alien[10];
Alien[] row3 = new Alien[10];
private Timer timer;
int DELAY = 16;
boolean reachedend = false;
Bullet bullet;
int lives;
public Board() {
setBackground(Color.BLACK);
addKeyListener(this);
lives = 3;
ship = new Ship();
fillAliens();
timer = new Timer(DELAY, this);
timer.start();
}
void fillAliens() {
for(int x=1;x<11;x++) {
row1[x-1] = new Alien(x*30+40,30);
row2[x-1] = new Alien(x*30+40,70);
row3[x-1] = new Alien(x*30+40,110);
}
}
void shoot() {
if(bullet==null) {
bullet = new Bullet(ship.x + ship.width/2,ship.y - ship.height/2,-1);
}
}
void drawAliens(Graphics2D g) {
g.setColor(Color.red);
for(int x=1;x<11;x++) {
if(row1[x-1].alive == true) {
g.fillRect(row1[x-1].x_loc, row1[x-1].y_loc, row1[x-1].width, row1[x-1].width);
}
if(row2[x-1].alive == true) {
g.fillRect(row2[x-1].x_loc, row2[x-1].y_loc, row2[x-1].width, row2[x-1].width);
}
if(row3[x-1].alive == true) {
g.fillRect(row3[x-1].x_loc, row3[x-1].y_loc, row3[x-1].width, row2[x-1].width);
}
}
}
public void addNotify() {
super.addNotify();
requestFocus();
}
void drawShip(Graphics2D g) {
g.fillRect(ship.x, ship.y, ship.width, ship.height);
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(lives>0) {
if (key == KeyEvent.VK_SPACE) {
shoot();
}
if (key == KeyEvent.VK_LEFT) {
if(ship.x>=5) {
ship.x -= 5;
}
}
if (key == KeyEvent.VK_RIGHT) {
if(ship.x+ship.width<434) {
ship.x += 5;
}
}
}
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
drawShip(g2);
drawAliens(g2);
drawBullet(g2);
drawAlienBullet(g2);
drawLives(g2);
}
private void drawLives(Graphics2D g2) {
g2.setColor(Color.white);
g2.drawString("Lives:", 10, 300);
for(int x=1; x<=lives;x++) {
g2.fillRect(15*x+30, 290, 10, 10);
}
}
private void drawBullet(Graphics2D g2) {
g2.setColor(Color.GREEN);
if(bullet!=null) {
g2.fillRect(bullet.x_loc, bullet.y_loc, bullet.width, bullet.height);
}
}
private void drawAlienBullet(Graphics2D g2) {
g2.setColor(Color.BLUE);
for(int x=0;x<10;x++) {
if(row3[x].bullet != null) {
g2.fillRect(row3[x].bullet.x_loc, row3[x].bullet.y_loc, row3[x].bullet.width, row3[x].bullet.height);
}
if(row2[x].bullet != null) {
g2.fillRect(row2[x].bullet.x_loc, row2[x].bullet.y_loc, row2[x].bullet.width, row2[x].bullet.height);
}
if(row1[x].bullet != null ) {
g2.fillRect(row1[x].bullet.x_loc, row1[x].bullet.y_loc, row1[x].bullet.width, row1[x].bullet.height);
}
}
}
private void bulletHitPlayer() {
for(int x=0;x<10;x++) {
if(row3[x].bullet != null) {
if(row3[x].bullet.y_loc >= 350) {
row3[x].bullet = null;
break;
}
}
if(row2[x].bullet != null) {
if(row2[x].bullet.y_loc >= 350) {
row2[x].bullet = null;
break;
}
}
if(row1[x].bullet != null) {
if(row1[x].bullet.y_loc >= 350) {
row1[x].bullet = null;
break;
}
}
if(row3[x].bullet != null && row3[x].bullet.y_loc + 10 >= ship.y && row3[x].bullet.y_loc <= ship.y + ship.height && row3[x].bullet.x_loc >= ship.x && row3[x].bullet.x_loc <= ship.x+ship.width) {
row3[x].bullet = null;
lives--;
break;
}
if(row2[x].bullet != null && row2[x].bullet.y_loc + 10 >= ship.y && row2[x].bullet.y_loc <= ship.y + ship.height && row2[x].bullet.x_loc >= ship.x && row2[x].bullet.x_loc <= ship.x+ship.width) {
row2[x].bullet = null;
lives--;
break;
}
if(row1[x].bullet != null && row1[x].bullet.y_loc + 10 >= ship.y && row1[x].bullet.y_loc <= ship.y + ship.height && row1[x].bullet.x_loc >= ship.x && row1[x].bullet.x_loc <= ship.x+ship.width) {
row1[x].bullet = null;
lives--;
break;
}
}
}
private void bulletHit() {
if(bullet!=null) {
for(int x=0;x<10;x++) {
if(row3[x].alive == true && bullet.y_loc >= row3[x].y_loc && bullet.y_loc <= row3[x].y_loc+row3[x].width && bullet.x_loc >= row3[x].x_loc && bullet.x_loc <= row3[x].x_loc+row3[x].width) {
row3[x].alive = false;
bullet=null;
break;
}
if(row2[x].alive == true && bullet.y_loc >= row2[x].y_loc && bullet.y_loc <= row2[x].y_loc+row2[x].width && bullet.x_loc >= row2[x].x_loc && bullet.x_loc <= row2[x].x_loc+row2[x].width) {
row2[x].alive = false;
bullet=null;
break;
}
if(row1[x].alive == true && bullet.y_loc >= row1[x].y_loc && bullet.y_loc <= row1[x].y_loc+row1[x].width && bullet.x_loc >= row1[x].x_loc && bullet.x_loc <= row1[x].x_loc+row1[x].width) {
row1[x].alive = false;
bullet=null;
break;
}
}
}
if(bullet!=null) {
if(bullet.y_loc<0) {
bullet=null;
}
}
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void actionPerformed(ActionEvent e) {
bulletHitPlayer();
bulletHit();
repaint();
}
}
Problem:
You draw your scene, whenever you press a key; and you draw your scene once on startup (see API and Tutorials) - But you should continuously redraw your scene by using the Timer properly.
How to solve:
When you create your Timer let it
either repeat itself timer.setRepeats(true);
or restart the Timer manually:
public void actionPerformed(ActionEvent e) {
bulletHitPlayer();
bulletHit();
repaint();
timer.restart(); //manually restart the timer
}
Related
I am creating a Binding of Isaac-esque Roguelike that is generated using an Array List using four Booleans. The four Booleans being North, East, South, and West. Corresponding to which doors is open.
The problem with Array Lists is that it can 'overlap'. For example, if I go east, than south, than west, than north, I'll be in a whole new room, and not the original.
Is there a way to stop this from happening, or at least prevent it? Such as if the room above room 1 (room 2) has south set to true, than north will be true in room 1 to connect the two rooms. Or if room 2 has south set to false, than north will be false in room 1 to stop overlap.
Here is my current code (I know my code isn't exactly clean and has a lot of magic numbers, but those shouldn't be important for this question)-
GameState:
public class GameState extends JFrame implements KeyListener {
Container contentPane=this.getContentPane();
Graphics bufferGraphics;
int characterX=463;
int characterY=486;
int oldCharacterX=463;
int oldCharacterY=486;
int xAxis;
int yAxis;
int minimapX=1300;
int minimapY=515;
Image characterNorth = CustomImages.createImageIcon("Images/characterNorth.jpg").getImage();
Image characterEast = CustomImages.createImageIcon("Images/characterEast.jpg").getImage();
Image characterSouth = CustomImages.createImageIcon("Images/characterSouth.jpg").getImage();
Image characterWest = CustomImages.createImageIcon("Images/characterWest.jpg").getImage();
Image brickWall = CustomImages.createImageIcon("Images/brickWall.jpg").getImage();
Image brickFloor = CustomImages.createImageIcon("Images/brickFloor.jpg").getImage();
Image character=characterNorth;
boolean pressed=false;
boolean minimap=true;
ArrayList<RoomState> map = new ArrayList<RoomState>();
RoomState currentRoom = new RoomState();
RoomState currentRoomState=new RoomState();
GameState() {
this.setBounds(0, 0, 1680, 1050);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}
public void move(int x, int y) { //Check Move
currentRoomState=currentRoomState.MoveToNextRoom(true, false, false, false);
currentRoomState=currentRoomState.MoveToNextRoom(false, true, false, false);
currentRoomState=currentRoomState.MoveToNextRoom(false, false, true, false);
currentRoomState=currentRoomState.MoveToNextRoom(false, false, false, true);
}
public void paint(Graphics g) { //Graphics
for(xAxis=58;xAxis<=858;xAxis=xAxis+50) {
for(yAxis=81;yAxis<=881;yAxis=yAxis+50) {
g.drawImage(brickFloor,xAxis,yAxis,null);
}
yAxis=31;
}
for(xAxis=8;xAxis<958;xAxis=xAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
yAxis=931;
for(xAxis=8;xAxis<=908;xAxis=xAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
xAxis=8;
for(yAxis=81;yAxis<=881;yAxis=yAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
xAxis=908;
for(yAxis=81;yAxis<=881;yAxis=yAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
if(currentRoom.northDoor) {
g.drawImage(brickFloor,458,31,null);
}
if(currentRoom.eastDoor) {
g.drawImage(brickFloor,908,481,null);
}
if(currentRoom.southDoor) {
g.drawImage(brickFloor,458,931,null);
}
if(currentRoom.westDoor) {
g.drawImage(brickFloor,8,481,null);
}
g.drawImage(character,characterX,characterY,null);
g.drawString("[ ]",minimapX,minimapY);
g.setColor(Color.RED);
g.drawString("[ ]", 1300, 515);
}
#Override
public void keyPressed(KeyEvent arg0) { //Character Rotation/Movement.
if(pressed==false) {
pressed=true;
oldCharacterX=characterX;
oldCharacterY=characterY;
if(arg0.getKeyCode() == KeyEvent.VK_W || arg0.getKeyCode() == KeyEvent.VK_UP) {
if(character==characterNorth) {
if(characterY>86 && characterX>13 && characterX<913) {
characterY=characterY-50;
}else if(currentRoom.northDoor && characterX==463) {
oldCharacterY=characterY;
characterY=characterY-50;
if(characterY==-14) {
if(currentRoom.rs_NorthDoor != null) {
currentRoom=currentRoom.rs_NorthDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,false, false, true, false);
currentRoom.rs_NorthDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapY=minimapY-10;
characterX=463;
characterY=936;
repaint();
}
}
}else {
character=characterNorth;
}
}
if(arg0.getKeyCode() == KeyEvent.VK_A || arg0.getKeyCode() == KeyEvent.VK_LEFT) {
if(character==characterWest && characterY>36 && characterY<926) {
if(characterX>63) {
oldCharacterX=characterX;
characterX=characterX-50;
}else if(currentRoom.westDoor && characterY==486) {
oldCharacterX=characterX;
characterX=characterX-50;
if(characterX==-37) {
if(currentRoom.rs_WestDoor != null) {
currentRoom = currentRoom.rs_WestDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,false, true, false, false);
currentRoom.rs_WestDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapX=minimapX-8;
characterX=913;
characterY=486;
repaint();
}
}
}else {
character=characterWest;
}
}
if(arg0.getKeyCode() == KeyEvent.VK_S || arg0.getKeyCode() == KeyEvent.VK_DOWN) {
if(character==characterSouth) {
if(characterY<871 && characterX>13 && characterX<913) {
oldCharacterY=characterY;
characterY=characterY+50;
}else if(currentRoom.southDoor && characterX==463) {
oldCharacterY=characterY;
characterY=characterY+50;
if(characterY==986) {
if(currentRoom.rs_SouthDoor != null) {
currentRoom=currentRoom.rs_SouthDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,true, false, false, false);
currentRoom.rs_SouthDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapY=minimapY+10;
characterX=463;
characterY=36;
repaint();
}
}
}else {
character=characterSouth;
}
}
if(arg0.getKeyCode() == KeyEvent.VK_D || arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
if(character==characterEast && characterY>36 && characterY<926) {
if(characterX<848) {
oldCharacterX=characterX;
characterX=characterX+50;
}else if(currentRoom.eastDoor && characterY==486) {
oldCharacterX=characterX;
characterX=characterX+50;
if(characterX==963) {
if(currentRoom.rs_EastDoor != null) {
currentRoom = currentRoom.rs_EastDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,false, false, false, true);
currentRoom.rs_EastDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapX=minimapX+8;
characterX=13;
characterY=486;
repaint();
}
}
}else {
character=characterEast;
}
}
if(oldCharacterX != characterX || oldCharacterY != characterY) {
repaint(oldCharacterX,oldCharacterY,40,40);
}
repaint(characterX,characterY,40,40);
}
}
#Override
public void keyReleased(KeyEvent arg0) { //Prevents Holding Down Keys.
if(arg0.getKeyCode() == KeyEvent.VK_W || arg0.getKeyCode() == KeyEvent.VK_UP) {
pressed=false;
}
if(arg0.getKeyCode() == KeyEvent.VK_A || arg0.getKeyCode() == KeyEvent.VK_LEFT) {
pressed=false;
}
if(arg0.getKeyCode() == KeyEvent.VK_S || arg0.getKeyCode() == KeyEvent.VK_DOWN) {
pressed=false;
}
if(arg0.getKeyCode() == KeyEvent.VK_D || arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
pressed=false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
RoomState:
public class RoomState {
boolean northDoor;
boolean eastDoor;
boolean southDoor;
boolean westDoor;
boolean doorsOpen;
int northRoll;
int eastRoll;
int southRoll;
int westRoll;
Random r=new Random();
//Reference to the adjacent rooms
RoomState rs_NorthDoor=null;
RoomState rs_EastDoor=null;
RoomState rs_SouthDoor=null;
RoomState rs_WestDoor=null;
RoomState() { //Initial
while(!doorsOpen) {
northRoll=r.nextInt(6)+1;
eastRoll=r.nextInt(6)+1;
southRoll=r.nextInt(6)+1;
westRoll=r.nextInt(6)+1;
if(northRoll==1) {
northDoor=true;
}else {
northDoor=false;
}
if(eastRoll==1) {
eastDoor=true;
}else {
eastDoor=false;
}
if(southRoll==1) {
southDoor=true;
}else {
southDoor=false;
}
if(westRoll==1) {
westDoor=true;
}else {
westDoor=false;
}
if(northDoor==false && eastDoor==false && southDoor==false && westDoor==false) {
doorsOpen=false;
}else {
doorsOpen=true;
}
}
}
RoomState(RoomState previousState, boolean north, boolean east, boolean south, boolean west) {
this();
if(north) {
rs_NorthDoor=previousState;
northDoor=true;
}else if(east) {
rs_EastDoor=previousState;
eastDoor=true;
}else if(south) {
rs_SouthDoor=previousState;
southDoor=true;
}else if(west) {
rs_WestDoor=previousState;
westDoor=true;
}
}
public RoomState MoveToNextRoom(boolean north, boolean east, boolean south, boolean west) {
if(north) {
if(rs_NorthDoor==null) {
rs_NorthDoor=new RoomState(this,north,east,south,west);
}
return rs_NorthDoor;
}
if(east) {
if(rs_EastDoor==null) {
rs_EastDoor=new RoomState(this,north,east,south,west);
}
return rs_EastDoor;
}
if(south) {
if(rs_SouthDoor==null) {
rs_SouthDoor=new RoomState(this,north,east,south,west);
}
return rs_SouthDoor;
}
if(west) {
if(rs_WestDoor==null) {
rs_WestDoor=new RoomState(this,north,east,south,west);
}
return rs_WestDoor;
}
return null;
}
}
Hello I'm fairly new to programming and this is my first time posting here so any help would be appreciated so:
my problem is that I"m trying to create some kind of 2D shooter game in java but I don't know if my simple game loop is good because when i shoot a missile it shoots a one every 20 ms and it's too fast and shoots a ton of missiles at once so is there any way to adjust it ? Like to keep some delay between every missile and the other??
and please tell me if i have problems or bad programming in my code !!
this is my game panel where most of the game happens and where my loop and adding missiles method in
public class GamePanel extends JPanel implements KeyListener {
Measurments mesure = new Measurments();
int panel_width = mesure.getUniversalWidth();
int panel_height = mesure.getUniversalHeight();
Timer timer;
Random rand = new Random();
ArrayList<Enemy> enemies = new ArrayList<>();
ArrayList<Missile> missiles = new ArrayList<>();
Player player = new Player(0, 0);
boolean up = false;
boolean down = false;
boolean right = false;
boolean left = false;
boolean isShooting = false;
boolean isRunning = true;
public boolean gameRunning() {
return isRunning;
}
int count = 5;
int missilesCount = 6;
public GamePanel() {
timer = new Timer(20, new ActionListener() {
public void actionPerformed(ActionEvent e) {
StartGame();
repaint();
}
});
setSize(panel_width, panel_height);
addKeyListener(this);
timer.start();
for (int i = 0; i < count; i++) {
addEnemy(new Enemy(rand.nextInt(750), rand.nextInt(500)));
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
player.paint(g2d);
for (int i = 0; i < enemies.size(); i++) {
Enemy temp = enemies.get(i);
temp.paint(g2d);
}
for (int i = 0; i < missiles.size(); i++) {
Missile mis = missiles.get(i);
mis.paint(g2d);
mis.behave();
}
}
public void StartGame() {
if (isRunning) {
runGame();
setBackground(Color.YELLOW);
} else {
setBackground(Color.BLACK);
}
}
public void runGame() {
update();
};
public void update() {
player.checkBorders();
checkColls();
if (up) {
player.updateUp();
}
if (down) {
player.updateDown();
}
if (right) {
player.updateRight();
}
if (left) {
player.updateLeft();
}
if (isShooting) {
for (int i = 0; i < 5; i++) {
missiles.add(new Missile(player.getX() + 16, player.getY() + 16));
}
}
for (int i = 0; i < missiles.size(); i++) {
Missile temp = missiles.get(i);
if (temp.getX() == panel_width) {
RemoveMissile(temp);
}
}
}
public void addEnemy(Enemy e) {
enemies.add(e);
}
public void removeEnemy(Enemy e) {
enemies.remove(e);
}
public void addMissile(Missile e) {
missiles.add(e);
}
public void RemoveMissile(Missile e) {
missiles.add(e);
}
public void checkColls() {
for (int i = 0; i < enemies.size(); i++) {
Enemy tempEnm = enemies.get(i);
for (int e = 0; e < missiles.size(); e++) {
Missile tempMis = missiles.get(e);
if (tempMis.missileRect().intersects(tempEnm.enemyRect())) {
enemies.remove(tempEnm);
missiles.remove(tempMis);
}
}
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_UP) {
up = true;
}
if (key == e.VK_DOWN) {
down = true;
}
if (key == e.VK_RIGHT) {
right = true;
}
if (key == e.VK_LEFT) {
left = true;
}
if (key == e.VK_ENTER) {
isRunning = true;
}
if (key == e.VK_SPACE) {
isShooting = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_UP) {
up = false;
}
if (key == e.VK_DOWN) {
down = false;
}
if (key == e.VK_RIGHT) {
right = false;
}
if (key == e.VK_LEFT) {
left = false;
}
if (key == e.VK_SPACE) {
isShooting = false;
}
}
public void keyTyped(KeyEvent e) {
}
}
Thanks in advance !!
private long fired = 0L;
public void update() {
...
// firing missiles: only if the missile count is less than the max., and the elapsed
// time is more than a limit (100 ms)
if ( isShooting && missiles.size() < missilesCount &&
( System.currentTimeMilis() - this.fired ) > 100 ) {
missiles.add( new Missile( player.getX() + 16, player.getY() + 16 ) );
// time of last firing
this.fired = System.currentTimeMilis();
}
...
}
public void RemoveMissile(Missile e) {
// as Guest is asked in another answer, this method should remove, not add...
missiles.remove(e);
}
I'm programming Checkers and having an issue where my checkers aren't moving. I'm using a Java Applet. It registers the fact that I click, but it's not moving the checker itself.
Here's my MouseClicked, I think that's where I'm having the problem:
public void mouseClicked(MouseEvent e) {
mouseX=e.getX();
mouseY=e.getY();
col = (mouseX-115)/100;
row = (mouseY-115)/100;
if(board[row][col].getPlayer()==player)
{ oldCol = col;
oldRow = row;
if(board[row][col].getPlayer()==0)
{
if(board[oldRow][oldCol].getPlayer()==1 && board[oldRow][oldCol].getKing()==false)
{
if(row==oldRow-1)
{
if(col==oldCol-1 || col==oldCol+1)
{
board[oldRow][oldCol].setPlayer(0);
board[row][col].setPlayer(1);
board[row][col].setKing(false);
}
}
}
else if(board[oldRow][oldCol].getPlayer()==1 && board[oldRow][oldCol].getKing()==true)
{
if(row==oldRow-1 || row==oldRow+1)
{
if(col==oldCol-1 || col==oldCol+1)
{
board[oldRow][oldCol].setPlayer(0);
board[row][col].setPlayer(1);
board[row][col].setKing(true);
}
}
}
else if(board[oldRow][oldCol].getPlayer()==2 && board[oldRow][oldCol].getKing()==true)
{
if(row==oldRow-1 || row==oldRow+1)
{
if(col==oldCol-1 || col==oldCol+1)
{
board[oldRow][oldCol].setPlayer(0);
board[row][col].setPlayer(2);
board[row][col].setKing(true);
}
}
}
else if(board[oldRow][oldCol].getPlayer()==2 && board[oldRow][oldCol].getKing()==false)
{
if(row==oldRow+1)
{
if(col==oldCol-1 || col==oldCol+1)
{
board[oldRow][oldCol].setPlayer(0);
board[row][col].setPlayer(2);
board[row][col].setKing(false);
}
}
}
}
}
repaint();
}
I am programming a game and when he go left the image should rotate left but it is not it is giving me and error:
Exception in thread "Thread-2" java.lang.NullPointerException
at Schoo.NewGame.TheRealGame.turnPlayer(TheRealGame.java:365)
at Schoo.NewGame.TheRealGame$2.run(TheRealGame.java:154)
at java.lang.Thread.run(Unknown Source)
Yes, i know that java.lang.NullPointerException means something is null but nothing should be null anyway here is the code on line 365:
g2.rotate(90.0+90.0+90.0);
line 154 just runs the method:
public static void turnPlayer(Direction d){
Graphics g = playerImage.getGraphics();
Graphics2D g2 = (Graphics2D) g;
if (d == Direction.LEFT){
if (p.getDirection() == Direction.LEFT){
return;
}
if (p.getDirection() == Direction.UP){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.RIGHT){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.DOWN){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
if (d == Direction.UP){
if (p.getDirection() == Direction.UP){
return;
}
if (p.getDirection() == Direction.RIGHT){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.DOWN){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.LEFT){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
if (d == Direction.RIGHT){
if (p.getDirection() == Direction.RIGHT){
return;
}
if (p.getDirection() == Direction.DOWN){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.LEFT){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.UP){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
if (d == Direction.DOWN){
if (p.getDirection() == Direction.DOWN){
return;
}
if (p.getDirection() == Direction.LEFT){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.UP){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.RIGHT){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
RepaintPlayer();
f.repaint();
playerImage.repaint();
}
and if you need the whole class:
public class TheRealGame{
private static boolean running = false;
private static boolean paused = false;
private static boolean right = false, left = false, up = false, down = false;
private static JFrame f;
private static ArrayList<JLabel> ae = new ArrayList<JLabel>();
private static Player p;
private static Playere pt;
private static JLabel playerImage;
private static boolean info = false;
private static JLabel iy, ix, im, in, iu;
public static void main(Playere playertype){
pt = playertype;
p = new Player(pt);
f = new JFrame();
f.setVisible(true);
f.setSize(700, 700);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyChar() == KeyEvent.VK_W){
up = true;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyChar() == KeyEvent.VK_A){
left = true;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyChar() == KeyEvent.VK_S){
down = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyChar() == KeyEvent.VK_D){
right = true;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE || e.getKeyCode() == KeyEvent.VK_ENTER){
p.attack();
}
if (e.getKeyCode() == KeyEvent.VK_F3){
if (info == true){
info = false;
iy.setVisible(false);
ix.setVisible(false);
im.setVisible(false);
in.setVisible(false);
iu.setVisible(false);
}else if (info == false){
info = true;
iy.setVisible(true);
ix.setVisible(true);
im.setVisible(true);
in.setVisible(true);
iu.setVisible(true);
}
}
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyChar() == KeyEvent.VK_W){
up = false;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyChar() == KeyEvent.VK_A){
left = false;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyChar() == KeyEvent.VK_S){
down = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyChar() == KeyEvent.VK_D){
right = false;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE || e.getKeyCode() == KeyEvent.VK_ENTER){
p.attack();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
});
iy = new JLabel();
ix = new JLabel();
im = new JLabel();
in = new JLabel();
iu = new JLabel();
iy.setLocation(0, 10);
ix.setLocation(0, 20);
im.setLocation(0, 30);
in.setLocation(0, 40);
iu.setLocation(0, 50);
iy.setBounds((int) iy.getLocation().getX(), (int) iy.getLocation().getY(), 100, 15);
ix.setBounds((int) ix.getLocation().getX(), (int) ix.getLocation().getY(), 100, 15);
im.setBounds((int) im.getLocation().getX(), (int) im.getLocation().getY(), 100, 15);
in.setBounds((int) in.getLocation().getX(), (int) in.getLocation().getY(), 100, 15);
iu.setBounds((int) iu.getLocation().getX(), (int) iu.getLocation().getY(), 100, 15);
f.add(ix);
f.add(iy);
f.add(im);
f.add(in);
f.add(iu);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("free play - tokyo ghoul");
Start();
p.Paint();
}
public static void resume(){
if (paused == false){
return;
}
}
public static void pause(){
if (paused == true){
return;
}
}
public static void Stop(){
if (running == false){
return;
}
running = false;
}
public static void Start(){
running = true;
new Thread(new Runnable(){
#Override
public void run() {
int last = 0, u = 0;
while (running == true){
if (paused != true){
if (up == true){
p.move(p.getX(), p.getY()-1);
if (p.getDirection() != Direction.UP){
turnPlayer(Direction.UP);
}
}
if (down == true){
p.move(p.getX(), p.getY()+1);
if (p.getDirection() != Direction.DOWN){
turnPlayer(Direction.DOWN);
}
}
if (left == true){
p.move(p.getX()-1, p.getY());
if (p.getDirection() != Direction.LEFT){
turnPlayer(Direction.LEFT);
}
}
if (right == true){
p.move(p.getX()+1, p.getY());
if (p.getDirection() != Direction.RIGHT){
turnPlayer(Direction.RIGHT);
}
}
if (info == true){
int l = 10-last;
iy.setText("y: "+p.getY());
ix.setText("x: "+p.getX());
im.setText("enemys: "+ae.size());
in.setText("next enemy: "+l);
iu.setText("Updated "+u+" times.");
RefreshInfo();
}
if (p.getY() == -337){
p.move(p.getX(), 337);
}
if (p.getY() == 337){
p.move(p.getX(), -337);
}
if (p.getX() == -349){
p.move(349, p.getY());
}
if (p.getX() == 349){
p.move(-349, p.getY());
}
RepaintAllLabels();
Enemy.UpdateAll();
if (info != true){
f.repaint();
}
if (last == 10){
Random r = new Random();
int x = 1+r.nextInt(2), y = 1+r.nextInt(2), distance = 1+r.nextInt(570), nx = 0, ny = 0;
if (x == 1){
}
last = 0;
}
last++;
u++;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
public static void RefreshInfo(){
f.remove(iy);
f.remove(ix);
f.remove(im);
f.remove(in);
f.remove(iu);
f.add(ix);
f.add(iy);
f.add(im);
f.add(in);
f.add(iu);
iy.setLocation(0, 10);
ix.setLocation(0, 20);
im.setLocation(0, 30);
in.setLocation(0, 40);
iu.setLocation(0, 50);
iu.setBounds((int) iu.getLocation().getX(), (int) iu.getLocation().getY(), 100, 15);
iy.setBounds((int) iy.getLocation().getX(), (int) iy.getLocation().getY(), 100, 15);
ix.setBounds((int) ix.getLocation().getX(), (int) ix.getLocation().getY(), 100, 15);
im.setBounds((int) im.getLocation().getX(), (int) im.getLocation().getY(), 100, 15);
in.setBounds((int) in.getLocation().getX(), (int) in.getLocation().getY(), 100, 15);
f.repaint();
}
public static void UpdateAll(){
}
public static void Paint(JLabel imgs, int x, int y, File file){
ImageIcon img = new ImageIcon(file.getPath());
imgs.setBounds(x, y, img.getIconWidth(), img.getIconHeight());
imgs.setLocation(x, y);
imgs.setVisible(true);
f.add(imgs);
imgs.setVisible(true);
}
public static void Repaint(JLabel l){
f.remove(l);
l.setBounds((int)l.getLocation().getX(), (int)l.getLocation().getY(), l.getWidth(), l.getHeight());
f.add(l);
}
public static void addAE(JLabel l){
ae.add(l);
}
public static void RepaintAllLabels(){
for (int i = 0; i < ae.size(); i++){
Repaint(ae.get(i));
}
}
public static void MovePlayer(int x, int y){
playerImage.setLocation(x, y);
playerImage.repaint();
f.repaint();
}
public static void RepaintPlayer(){
if (p.isAttacking()){
if (pt == Playere.Kaneki){
ImageIcon img = new ImageIcon(StartMenu.class.getResource("/Schoo/NewGame/Kaneki_hit.png"));
playerImage = new JLabel(img);
}
if (pt == Playere.Touka){
ImageIcon img = new ImageIcon(StartMenu.class.getResource("/Schoo/NewGame/touka_hit.png"));
playerImage = new JLabel(img);
}
}else{
if (pt == Playere.Kaneki){
ImageIcon img = new ImageIcon(StartMenu.class.getResource("/Schoo/NewGame/Kaneki_walk.png"));
playerImage = new JLabel(img);
}
if (pt == Playere.Touka){
ImageIcon img = new ImageIcon(StartMenu.class.getResource("/Schoo/NewGame/touka_walk.png"));
playerImage = new JLabel(img);
}
}
playerImage.setVisible(false);
playerImage.repaint();
playerImage.setVisible(true);
playerImage.repaint();
playerImage.setVisible(true);
MovePlayer(p.getX(), p.getY());
f.repaint();
}
public static void paintplayer(){
if (pt == Playere.Kaneki){
playerImage = new JLabel(new ImageIcon(StartMenu.class.getResource("/schoo/NewGame/kaneki_walk.png")));
if (playerImage == null){
System.out.println("[ERROR THIS WAS THE ERROR THE WHOLE TIME!!");
return;
}
ImageIcon imgs = new ImageIcon(StartMenu.class.getResource("/schoo/NewGame/kaneki_walk.png"));
playerImage.setBounds(p.getX(), p.getY(), imgs.getIconWidth(), imgs.getIconHeight());
playerImage.setLocation(0, 0);
playerImage.setVisible(true);
f.add(playerImage);
playerImage.setVisible(true);
}
if (pt == Playere.Touka){
playerImage = new JLabel(new ImageIcon(StartMenu.class.getResource("/schoo/NewGame/touka_walk.png")));
playerImage.setBounds(p.getX(), p.getY(), new ImageIcon(StartMenu.class.getResource("/schoo/NewGame/touka_walk.png")).getIconWidth(), new ImageIcon(StartMenu.class.getResource("/schoo/NewGame/touka_walk.png")).getIconHeight());
playerImage.setLocation(p.getX(), p.getY());
playerImage.setVisible(true);
f.add(playerImage);
playerImage.setVisible(true);
}
}
public static void turnPlayer(Direction d){
Graphics g = playerImage.getGraphics();
Graphics2D g2 = (Graphics2D) g;
if (d == Direction.LEFT){
if (p.getDirection() == Direction.LEFT){
return;
}
if (p.getDirection() == Direction.UP){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.RIGHT){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.DOWN){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
if (d == Direction.UP){
if (p.getDirection() == Direction.UP){
return;
}
if (p.getDirection() == Direction.RIGHT){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.DOWN){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.LEFT){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
if (d == Direction.RIGHT){
if (p.getDirection() == Direction.RIGHT){
return;
}
if (p.getDirection() == Direction.DOWN){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.LEFT){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.UP){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
if (d == Direction.DOWN){
if (p.getDirection() == Direction.DOWN){
return;
}
if (p.getDirection() == Direction.LEFT){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.UP){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.RIGHT){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
RepaintPlayer();
f.repaint();
playerImage.repaint();
}
public static enum Direction{
LEFT, UP, RIGHT, DOWN;
}
}
Thank you for taking your time to help me!
You can use the Rotated Icon. This class does all the rotation logic for you. You just need to specify the degrees of rotation.
So the basic code to create the label would be:
RotatedIcon icon = new RotatedIcon( new ImageIcon(...) );
JLabel player = new JLabel( icon );
Then when you want to rotate the Icon you can use:
icon.setDegrees(...);
player.repaint();
That's not how you do Swing Graphics -- you shouldn't be calling getGraphics() on a component since there is great risk that the object will either be null or non-functioning. Instead if this were my program, I'd get the actual image used, rotate it in all 4 directions (3 plus the original), make ImageIcons out of these images, store them in a collection, or better a HashMap<Direction, Icon>, say called playerDirectionIconMap, and then use them without fear. Then to get the proper icon, I'd just call something like,
// this method should probably not be static
public void turnPlayer(Direction d){
playerImage.setIcon(playerDirectionIconMap.get(p.getDirection()));
// .... other code?
}
Note that the turnPlayer(...) method should not be static as this suggests a broken design that needs to be fixed.
Also note that:
The rotate method uses radians and not degrees, so instead of 90.0, use Math.PI / 2.
You will want to use the rotate method that takes a center point so that your rotation isn't around 0, 0.
I just now trying to make a game where there are few borders on the map, which is being generated from a text document. The text document has 1s and 0s where ther is 1 it shows a wall. So how do I make it so the character stops infront of the wall
My Code:
MAIN CLASS:
public class JavaGame {
public static void main(String[] args) {
final Platno p = new Platno();
final JFrame okno = new JFrame("Test");
Mapa map = new Mapa();
okno.setResizable(false);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
okno.setSize(800, 600);
okno.setVisible(true);
map.nacti();
okno.add(p);
p.mapa = map;
okno.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int kod = e.getKeyCode();
if(kod == KeyEvent.VK_LEFT)
{
Platno.x -= 3;
p.repaint();
}
else if(kod == KeyEvent.VK_RIGHT)
{
Platno.x +=3;
p.repaint();
}
else if(kod == KeyEvent.VK_UP)
{
Platno.y -=3;
p.repaint();
}
else if(kod == KeyEvent.VK_DOWN)
{
Platno.y +=3;
p.repaint();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
/* Timer = new Timer(1, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
Platno.y -=3;
p.repaint();
}
}); */
}`
Map loader class:
public void nacti()
{
try (BufferedReader br = new BufferedReader(new FileReader("map1-1.txt")))
{
String radek;
int cisloRadku = 0;
while((radek = br.readLine()) != null)
{
for(int i = 0; i < radek.length(); i++)
{
char znak = radek.charAt(i);
int hodnota = Integer.parseInt(String.valueOf(znak));
pole[i][cisloRadku] = hodnota;
}
cisloRadku++;
}
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
}
public void vykresli(Graphics g)
{
try {
wall = ImageIO.read(ClassLoader.getSystemResource("Images/wall.gif"));
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
for(int i = 0; i < pole[0].length; i++)
{
for(int j = 0; j < pole.length; j++)
{
if(pole[j][i] == 1)
{
g.setColor(Color.RED);
// g.fillRect(j*40, i*40, 40, 40);
g.drawImage(wall, j*40, i*40, null);
}
}
}
}`
and the Hero class:
public class Hero {
public int poziceX;
public int poziceY;
public static boolean upB = false;
public static boolean downB = false;
public static boolean rightB = false;
public static boolean leftB = false;
BufferedImage up;
BufferedImage down;
BufferedImage right;
BufferedImage left;
public Hero()
{
try {
up = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Up.png"));
down = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Down.png"));
right = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Right.png"));
left = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Left.png"));
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
}
public void vykreslit(Graphics g)
{
if(upB == true)
{
g.drawImage(up, poziceX, poziceX, null);
}
else if(downB == true)
{
g.drawImage(down, poziceX, poziceX, null);
}
else if(leftB == true)
{
g.drawImage(left, poziceX, poziceX, null);
}
else if(rightB == true)
{
g.drawImage(right, poziceX, poziceX, null);
}
}`
Thanks for your help :)
You could calculate the 'future position' for a move, and test for collisions.
If a collision occur, dont'move, otherwise you're ok to move.
See if this logic can help you:
public boolean willCollide(int row, int col, Board map)
{
return map[row][col] == 1;
}
public void moveLeft(Hero hero, Board map)
{
//watch for index out of bounds!
int futureCol = hero.y - 1;
if (! willCollide(hero.row, futureCol)
hero.y = futureCol;
}