Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: My 2D Tile Game Lag (Caused by loop) Looking for an alternate method of rendering

  1. #1
    Junior Member
    Join Date
    Sep 2013
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Question My 2D Tile Game Lag (Caused by loop) Looking for an alternate method of rendering

    So the following is my code for the Terrian Generation of my game, however the way i have it rendering all the tile rectangles as opposed to just rendering whats visable on my JFrame causes lots of lag. All suggestions welcomed!

    These are the variables and Rectangles inside _TerrianGen.class
            //CHUNK
    		static int chunkx =2048;
    		static int chunky =2048;
     
    	//RECTANGLES
    		public static Rectangle[][] tile = new Rectangle[64][64];
    		static int[][] blockType = new int[64][64];
    		//0=Grass 1=Dirt 2=Stone 10=Brick 11=Coal 12=Iron 21=Gold 22=Diamond -1=null

    This is the Init() code
    for (int x =0; x < chunkx-32; x+=32){
    			for (int y=0; y < chunky-32; y+=32){
    				tile[y/32][x/32] = new Rectangle(x, y, 32, 32);
    				blockType[y/32][x/32] = -1;
    			}
     
    		}
    		for (int i =0; i < 20; i++){
    			blockType[10][i] = 0;
    		}

    Then my render code... where i believe the problem is
    public static void render(Graphics g){
    		for (int x =0 ; x < chunkx-32; x++){
    			for (int y =0; y < chunky-32; y++){
     
     
    				//CREATING BLOCKS
    		//		if (_Mouse.mouse.intersects(tile[x/32][y/32]) && delete && blockType[x/32][y/32] == -1 && _Inventory.hand){
    		//			blockType[x/32][y/32] = 10;
    		//		}
    		//		
    				//DELETE BLOCKS
    		//		if (_Mouse.mouse.intersects(tile[x/32][y/32]) && delete && blockType[x/32][y/32] != -1 && _Inventory.pick){
    		//			blockType[x/32][y/32] = -1;
    		//		}
     
    				//SPAWNING BLOCKS
    				switch (blockType[x/32][y/32]){
    				case 0:		g.drawImage(_LoadImages.image[0], tile[x/32][y/32].x+(Main.PLAYEROSx*2), tile[x/32][y/32].y+(Main.PLAYEROSy*2), 32, 32, null);
    						break;
    				case 1:		g.drawImage(_LoadImages.image[1], tile[x/32][y/32].x+(Main.PLAYEROSx*2), tile[x/32][y/32].y+(Main.PLAYEROSy*2), 32, 32, null);
    						break;
    				case 2:		g.drawImage(_LoadImages.image[2], tile[x/32][y/32].x+(Main.PLAYEROSx*2), tile[x/32][y/32].y+(Main.PLAYEROSy*2), 32, 32, null);
    						break;
    				case 10:	g.drawImage(_LoadImages.image[10], tile[x/32][y/32].x+(Main.PLAYEROSx*2), tile[x/32][y/32].y+(Main.PLAYEROSy*2), 32, 32, null);
    						break;
    				case 11:	g.drawImage(_LoadImages.image[11], tile[x/32][y/32].x+(Main.PLAYEROSx*2), tile[x/32][y/32].y+(Main.PLAYEROSy*2), 32, 32, null);
    						break;
    				case 12:	g.drawImage(_LoadImages.image[12], tile[x/32][y/32].x+(Main.PLAYEROSx*2), tile[x/32][y/32].y+(Main.PLAYEROSy*2), 32, 32, null);
    						break;
    				case 21:	g.drawImage(_LoadImages.image[21], tile[x/32][y/32].x+(Main.PLAYEROSx*2), tile[x/32][y/32].y+(Main.PLAYEROSy*2), 32, 32, null);
    						break;
    				case 22:	g.drawImage(_LoadImages.image[22], tile[x/32][y/32].x+(Main.PLAYEROSx*2), tile[x/32][y/32].y+(Main.PLAYEROSy*2), 32, 32, null);
    						break;
    				}
     
    			}
    		}
     
    	}

    Main.java
    package main;
     
    import main.controls._KeyBoard;
    import main.controls._Mouse;
    import main.player._Jump;
    import main.player._Player;
    import main.terrian.*;
     
    import java.awt.Canvas;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.awt.image.BufferStrategy;
     
    import javax.swing.JFrame;
     
    public class Main extends Canvas implements Runnable{
    	private static final long serialVersionUID = 1L;
     
    	//PLAYER
    	Rectangle p1;
    	public static double windowROT =0;
    	public static int PLAYEROSx=0;
    	public static int PLAYEROSy=0;
    	private static _Player player;
     
    	//JFRAME
    	public static int windowWidth = 600;
    	public static int windowHeight = 400;
    	public static int scale = 2;
     
    	//SCRIPT
    	public static boolean running = false;
    	public Thread gameThread;
     
    	//FPS
    	public int currentFPS = 0;
        public static int FPS = 0;
        public long start = 0;
     
    	public void init(){
    		this.addKeyListener(new _KeyBoard());
    		this.addMouseListener(new _Mouse());
    		player = new _Player();
    		new _LoadImages();
    		new _TerrianGen();
    	}
    	public synchronized void start(){
    		if(running)return;
    		running = true;
    		gameThread = new Thread(this);
    		gameThread.start();
    	}
    	public synchronized void stop(){
    		if(!running)return;
    		running = false;
    		try {
    			gameThread.join();
    		} catch (InterruptedException e) {
    			e.printStackTrace();
     
    		}
    	}
    	public void run() {
    		init();
     
    		long lastTime = System.nanoTime();
    		final double amountOfTicks = 60D;
    		double ns = 1000000000 / amountOfTicks;
    		double delta = 0;
     
    		while(running){
    			long now = System.nanoTime();
    			delta += (now - lastTime) / ns;
    			lastTime = now;
    			if(delta >= 1){
    				tick();delta--;
     
    			}
    			render();
     
    		}
    		stop();
    	}
    	public void tick(){
    		_Player.tick();
     
    		_Jump.tick();
     
     
    		currentFPS++;
            if(System.currentTimeMillis() - start >= 1000) {
            	FPS = currentFPS;currentFPS = 0;
            	start = System.currentTimeMillis();
            }
    	}
    	public void render(){
     
    		BufferStrategy bs = this.getBufferStrategy();
    		if(bs ==  null){
    			createBufferStrategy(3);
    			return;
    		}
    		Graphics g = bs.getDrawGraphics();
    		//RENDER HERE
     
    			_Background.render(g);
     
    			_Player.render(g);
     
    		//END RENDER
    		g.dispose();
    		bs.show();
    	}
    	public static void main (String[] args) {
    		Main game = new Main();
    		game.setPreferredSize(new Dimension(windowWidth * scale, windowHeight * scale));
    		game.setMaximumSize(new Dimension(windowWidth * scale, windowHeight * scale));
    		game.setMinimumSize(new Dimension(windowWidth * scale, windowHeight * scale));
     
    		JFrame frame = new JFrame("Void v2.0 Alpha");
    		frame.setSize(windowWidth * scale, windowHeight * scale);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setResizable(false);
    		frame.add(game);
    		frame.setVisible(true);
    		frame.setLocationRelativeTo(null);
     
    		game.start();
    	}
    	public static _Player getPlayer(){
    		return player;
    	}
    	public static int getFPS() {
            return FPS;
        }
     
     
    }
    Last edited by Cekeh; January 19th, 2014 at 06:59 PM. Reason: For additional help.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,290
    My Mood
    Mellow
    Thanks
    191
    Thanked 668 Times in 655 Posts

    Default Re: My 2D Tile Game Lag (Caused by loop) Looking for an alternate method of rendering

    Have you used a profiler to determine that the code you've posted is the source of the lag, or are you guessing?

  3. #3
    Junior Member
    Join Date
    Sep 2013
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My 2D Tile Game Lag (Caused by loop) Looking for an alternate method of rendering

    When I remove the render chunk of the code, the lag disappears. So yeah I suppose you could say its a guess. I can post all my code if it would be easier.

    Also I'm fairly new to java, only learning off of tutorials and some java books I have lying around the house. So if you have any tips, please state them as I would love to learn more.

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,290
    My Mood
    Mellow
    Thanks
    191
    Thanked 668 Times in 655 Posts

    Default Re: My 2D Tile Game Lag (Caused by loop) Looking for an alternate method of rendering

    So you have some evidence that's the source of the lag. Didn't want to waste time looking at code that wasn't the problem. The key areas to investigate are: large nested for loops, in the tens of thousands, the images are being loaded each time from a slow resource, and/or the thread that does the drawing is being slept somewhere else.

    Do you have a loop that controls the pace of the game and/or "sleeps the thread" somewhere? If so post that. What I'm asking for might be your game loop. Either way, post that.

    If one reduces the code you posted to code that actually does something, there's a nested for loop and a switch statement. How large can that nested for loop be? What's the maximum (chunkx - 32) * (chunky - 32)? Then in the switch statement, what does _LoadImages do? Are the images being loaded already in memory or are they being obtained from a laggy resource like a hard drive or the internet? Why do you even need the switch() statement? It seems the only difference in the statement in the case blocks is the index which is the same as the switch parameter. Why not use that parameter to indicate the desired image and replace the entire switch() logic with a single line of code. That code will be more elegant, but it won't change performance.

    Everybody's "new to Java" and writing (or wanting to write) a complex graphical game. Don't get me started.

  5. #5
    Junior Member
    Join Date
    Sep 2013
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My 2D Tile Game Lag (Caused by loop) Looking for an alternate method of rendering

    _LoadImages, just simply stores a buffered image that was inside the init() method. Yes my game has a loop timer of 60fps.

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,290
    My Mood
    Mellow
    Thanks
    191
    Thanked 668 Times in 655 Posts

    Default Re: My 2D Tile Game Lag (Caused by loop) Looking for an alternate method of rendering

    It's interesting that I asked several questions, suggested a couple places to look, and asked for code and you gave such a short answer that covers about 20% of what I asked. How are we supposed to help with so little information?

  7. #7
    Junior Member
    Join Date
    Sep 2013
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My 2D Tile Game Lag (Caused by loop) Looking for an alternate method of rendering

    Im sorry I'm very busy and not at my computer much lately, I've been posting from my phone. I will answer more as soon as I get a good look at the code myself.

Similar Threads

  1. Replies: 0
    Last Post: October 25th, 2013, 03:28 PM
  2. Game rendering
    By Whoameye2u in forum What's Wrong With My Code?
    Replies: 1
    Last Post: September 20th, 2013, 03:33 PM
  3. [SOLVED] Tile puzzle game getting tiles to move (help)
    By thatguy in forum What's Wrong With My Code?
    Replies: 7
    Last Post: March 5th, 2013, 05:18 PM
  4. OutOfMemoryError caused in a loop at new BufferedImage
    By mame in forum AWT / Java Swing
    Replies: 1
    Last Post: January 28th, 2011, 05:37 PM
  5. Alternative to the scanner method
    By Harrisk9 in forum Java SE APIs
    Replies: 2
    Last Post: November 28th, 2009, 09:30 PM

Tags for this Thread