[java] Choppy Animation

Started by
2 comments, last by mrlinkedlist 13 years, 12 months ago
I'm trying to do a very simple animation test, moving an oval around a screen. However, the animation is very choppy and the oval seems to sputter when I hold down either left or right. The code that follows is a JPanel that runs the simple animation movement. Perhaps it is the way I handle the main game loop? Any help would be greatly appreciated.


	public class Canvas extends JPanel implements Runnable{

	private static Image screen;
	private static Graphics buffer;
	private static KeyboardInput keyboard = new KeyboardInput();
	
	private int x = 0;
	
	public Canvas(){
		super();
		
		//set up the keyboard for input
		this.setFocusable(true);
		this.requestFocus();
		this.addKeyListener(keyboard);
	}
	

	public void run() {
		
		//create a buffer screen for double buffering
		screen = createImage(800, 600);
		buffer = screen.getGraphics();
		
		 
		while(true){
			
			//get input and update position
			update();
			
			//render to the buffer
			render();
			
			//paint the buffer to the screen
			paintToScreen();
			
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				
			}
			
		}
		
	}
	
	
	private void update(){
		
                //get the keys being pressed
		keyboard.poll();
		processInput();
	}
	
	private void render(){
		
		buffer.clearRect(0, 0, 800, 600);
		buffer.setColor(Color.DARK_GRAY);
		buffer.fillRect(0, 0, 800, 600);
		buffer.setColor(Color.black);
		buffer.fillOval(x, 100, 20, 20);
	}
	
	private void paintToScreen(){
		
		Graphics g = this.getGraphics();
		
		g.drawImage(screen, 0, 0, null);
		
		Toolkit.getDefaultToolkit().sync();
		
		g.dispose();
	}
	
	private void processInput() {
		    if( keyboard.keyDown( KeyEvent.VK_RIGHT ) ) {
		
		    	x += 5;
		    }
		    else if( keyboard.keyDown( KeyEvent.VK_LEFT ) ) {
			      
		    	x -= 5;
		    }
	  }
}


Advertisement
Perhaps the problem has to do with the way you are moving the rect...

x += 5;

I haven't tried your code out, but if your framerate is changing, then the speed at which you move is changing. Do you see what I mean. Perhaps you should try moving by some value, such as 0.01 * time_since_last_frame. That way no matter how many clock cycles have passed, the object will move at the same speed.

Also, check this out if you haven't already...

Java Games: Active Rendering

I think, therefore I am. I think? - "George Carlin"
My Website: Indie Game Programming

My Twitter: https://twitter.com/indieprogram

My Book: http://amzn.com/1305076532

Obligatory "fix your timestep" article reference
Thank you both very much for the replies. I will check out the article.

This topic is closed to new replies.

Advertisement