Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (523)
Games in Android Showcase (127)
games submitted by our members
Games in WIP (591)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Game lagging horribly  (Read 662 times)
0 Members and 1 Guest are viewing this topic.
Offline Tiersile

Junior Newbie





« Posted 2013-10-24 17:22:36 »

My game is lagging horribly... I'm running it on a timer, and once I get to about 15 enemies on the screen, it lags. Does anyone have any suggestions? Sorry for bad code, I'm a fairly new programmer.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;

public class GameFrame extends JPanel implements ActionListener {

   Timer mainTimer;
   Player player;

   public static int level = 1;

   static ArrayList<Enemy> enemies = new ArrayList<Enemy>();
   static ArrayList<Missile> missiles = new ArrayList<Missile>();

   Random rand = new Random();

   // starts the game timer and starts the game
   public GameFrame() {
      setFocusable(true);
      player = new Player(150, 450);
      addKeyListener(new KeyAdapt(player));

      mainTimer = new Timer(10, this);
      mainTimer.start();

      startGame();

   }

   // paints the images to the game window
   public void paint(Graphics g) {
      super.paint(g);
      Graphics2D g2d = (Graphics2D) g;

      // draws the background
      ImageIcon bg = new ImageIcon(getClass().getResource("background.png"));
      g2d.drawImage(bg.getImage(), 0, 0, null);

      // draws the stats and upgrade panels
      ImageIcon stats = new ImageIcon(getClass().getResource("stats.png"));
      g2d.drawImage(stats.getImage(), 530, 0, null);

      ImageIcon ug = new ImageIcon(getClass().getResource("upgrades.png"));
      g2d.drawImage(ug.getImage(), 530, 250, null);

      player.draw(g2d);

      for (int i = 0; i < enemies.size(); i++) {
         Enemy tempEnemy = enemies.get(i);
         tempEnemy.draw(g2d);
      }

      for (int i = 0; i < missiles.size(); i++) {
         Missile m = missiles.get(i);
         m.draw(g2d);
      }

      // displays what level you are on, and your points
      g2d.drawString("Level :" + level, 550, 50);
      g2d.drawString("Enemy count: " + enemies.size(), 550, 70);
      g2d.drawString("Health :" + Player.health, 550, 90);
      g2d.drawString("Speed :" + Player.speed, 550, 110);
      g2d.drawString("Missile Count :" + Player.missileCount, 550, 130);
      g2d.drawString("Damage :" + Player.missilePower, 550, 150);

      // displays the upgrades available and how much they cost
      // speed
      g2d.drawString("1: +1 Speed", 535, 320);
      g2d.drawString("" + Player.speed * 10, 620, 320);
      // health
      g2d.drawString("2: " + (Player.healthpool + 5) + " health", 535, 340);
      g2d.drawString("" + Player.healthpool * 10, 620, 340);
      // missileCount
      g2d.drawString("3: +1 missile", 535, 360);
      g2d.drawString("" + Player.missileCount * 3, 620, 360);
      // missilePower
      g2d.drawString("4: +1 Damage", 535, 380);
      g2d.drawString("" + Player.missilePower * 6, 620, 380);
      // points
      g2d.drawString("Points :" + Player.points, 535, 400);
      //instructions
      g2d.drawString("Instructions: press", 535, 410);
      g2d.drawString("the corresponding", 535, 420);
      g2d.drawString("number on the left", 535, 430);
      g2d.drawString("to upgrade.", 535, 440);

   }

   // controls actions, checks if game has ended
   public void actionPerformed(ActionEvent arg0) {
      player.update();

      for (int i = 0; i < enemies.size(); i++) {
         Enemy tempEnemy = enemies.get(i);
         tempEnemy.update();
      }

      for (int i = 0; i < missiles.size(); i++) {
         Missile m = missiles.get(i);
         m.update();
      }

      checkEnd();
      repaint();
      try{
         Thread.sleep(20);
      }catch(InterruptedException ex){}
   }

   // adds enemies
   public void addEnemy(Enemy e) {
      enemies.add(e);
   }

   // removies enemies
   public static void removeEnemy(Enemy e) {
      enemies.remove(e);
   }

   // arraylist to store the number of enemies
   public static ArrayList<Enemy> getEnemyList() {
      return enemies;
   }

   // adds missiles
   public static void addMissile(Missile m) {
      missiles.add(m);
   }

   // removes missiles
   public static void removeMissile(Missile m) {
      missiles.remove(m);
   }

   // arraylist to store the number of missiles
   public static ArrayList<Missile> getMissileList() {
      return missiles;
   }

   // starts the game, loads up enemies
   public void startGame() {
      int enemyOneCount;
      int enemyTwoCount;

      enemyOneCount = level * 2;
      enemyTwoCount = level - 9;
      for (int i = 0; i < enemyOneCount; i++) {
         addEnemy(new EnemyOne(rand.nextInt(400), -10 + -rand.nextInt(600)));
      }
      if (level >= 10) {
         for (int i = 0; i < enemyTwoCount; i++) {
            addEnemy(new EnemyTwo(rand.nextInt(400), -10+ -rand.nextInt(600)));
         }
      }
   }

   // checks if the level is over
   public void checkEnd() {
      if (enemies.size() == 0) {
         if (Player.health > 0) {
            level++;
            enemies.clear();
            missiles.clear();
            startGame();
         } else {
            JOptionPane.showMessageDialog(null,"You lose! You made it to level " + level);
            System.exit(0);
         }
      }
   }
}
Offline Troncoso

JGO Coder


Medals: 20



« Reply #1 - Posted 2013-10-24 17:59:13 »

You are creating new resources in every frame:

1  
2  
3  
ImageIcon bg = new ImageIcon(getClass().getResource("background.png"));

ImageIcon ug = new ImageIcon(getClass().getResource("upgrades.png"));


I don't see your Enemy class in here, but if you are doing something similar with them, then that could cause your proposed issues.

Create all your resources before starting your game loop, then just reference those.
Offline Tiersile

Junior Newbie





« Reply #2 - Posted 2013-10-24 18:02:58 »

Do you have a skype or a website I could upload my project file to for you to look at? I see what you're saying, but I'm not sure where I should place those resources. I'm looking at it now
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Dxu1994
« Reply #3 - Posted 2013-10-24 18:04:36 »

1. Don't be loading assets every time you need to render something. If possible, use a cache.
2. Use BufferedImage instead of ImageIcon. ImageIcon is just for that - for icons!
3. Use a BufferStategy to render, this ensures GPU-page flipping on some hardware.
4. Convert BufferedImages to device-compatible format before displaying them.

Offline Troncoso

JGO Coder


Medals: 20



« Reply #4 - Posted 2013-10-24 18:05:12 »

Literally just pull those declarations out of the paint method and make them fields, like you have the Player object. You don't even need to write any extra code.

Oh, as well. Look up double buffering for Java2D. That'd be helpful.
Offline Dxu1994
« Reply #5 - Posted 2013-10-24 18:12:57 »

1. Instead of using new ImageIcon(blah) every time in paint(), create some BufferedImage fields and reference them in paint().
2. Load BufferedImages in your constructor with ImageIO.read().
3. Try and switch to a BufferStategy if you can, this will greatly improve performance.
4. Use this code to create a device-compatible image:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
public static BufferedImage toCompatibleImage(BufferedImage image, boolean override, boolean disposeOld) {
        if (image.getColorModel().equals(gfxConfig.getColorModel()) && !override) {
            return image;
        }
        BufferedImage newImage = gfxConfig.createCompatibleImage(image.getWidth(), image.getHeight(), image.getTransparency());
        Graphics2D g2d = newImage.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
        if (disposeOld) {
            image.flush();
        }

        return newImage;
    }

Offline Tiersile

Junior Newbie





« Reply #6 - Posted 2013-10-24 18:13:37 »

Okay, I did that. I'm looking into using BufferedImages now, reading up on it.  Smiley Thank you for the help both of you
Offline Jimmt
« League of Dukes »

JGO Kernel


Medals: 138
Projects: 4
Exp: 3 years



« Reply #7 - Posted 2013-10-25 05:28:16 »

I would not recommend putting Thread.sleep in your actionPerformed() method. Because you are running on the main thread, all you are doing is slowing down all processes for 20 ms (lag).
Offline Tiersile

Junior Newbie





« Reply #8 - Posted 2013-10-25 11:16:35 »

I would not recommend putting Thread.sleep in your actionPerformed() method. Because you are running on the main thread, all you are doing is slowing down all processes for 20 ms (lag).
Thank you! I put that in there originally to try to solve the issue by putting the thread to sleep, but I forgot to take it out. I appreciate everyone's help.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

trollwarrior1 (34 views)
2014-11-22 12:13:56

xFryIx (73 views)
2014-11-13 12:34:49

digdugdiggy (52 views)
2014-11-12 21:11:50

digdugdiggy (46 views)
2014-11-12 21:10:15

digdugdiggy (40 views)
2014-11-12 21:09:33

kovacsa (66 views)
2014-11-07 19:57:14

TehJavaDev (70 views)
2014-11-03 22:04:50

BurntPizza (68 views)
2014-11-03 18:54:52

moogie (83 views)
2014-11-03 06:22:04

CopyableCougar4 (82 views)
2014-11-01 23:36:41
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!