Skip to main content
GameDev.net gamedev.net
🔒 Locked

[java] Slow Loop Logic

Started by Jekler Dec 28, 2005 at 3:10 PM 0 replies 1.2k views
Original Post
Jekler
Jekler
I have a problem with the logic of my program executing slowly for some reason. I can't get my simple Pong game to run smoothly. It's obviously not too graphics intensive as I've seen far more powerful JOGL applications run just fine. I keep examining source code from other applications, comparing, and trying to fine-tune mine, but nothing seems to work. My problem is that the only way to control the ball's speed is to have the ball's thread (which doesn't do anything except move the ball) sleep for shorter periods of time. If I increment the ball's position anymore than 1 pixel at a time (i.e. the magnitude is greater than 1), the game looks choppy. Should I be going about this a different way? This is the section of code that moves the ball.

private void move()
{
	if((x >= TOP_BOUNDARY) ||
	   (y >= LEFT_BOUNDARY) || 
	   (y <= 0)   ||
	   (x <= 0))
		{
			angle += Math.PI / 2;
			if(angle > Math.PI * 2)
			{
                                // Keep the angle between 0 and 360 degrees
				angle -= Math.PI * 2;
			}
		}
		
	x += magnitude * Math.sin(angle);
	y += magnitude * Math.cos(angle);
}

public void run() {
	while(Thread.currentThread() == ballThread)
	{
		start_time = System.currentTimeMillis();
		move();
		try {
			delay += (System.currentTimeMillis() - start_time);
			Thread.sleep(16 - delay);
		} catch(InterruptedException e) {}
	}

Funkapotamus
Funkapotamus
Most games are single threaded. Your choppyness is probably the result of the ball's thread running adjacent to the game's main loop. Also, try basing movement off of the time each frame took (delta). This way things won't skip if you drop a frame.

Try doing everything in one thread:

int resolution = 1000; // 1000ms/secondint fps = 60; // Desired FPSlong delay = resolution / fps;public void run() {while(Thread.currentThread() == gameThread){	currentFrameTime = System.currentTimeMillis();		delta = currentFrameTime - lastFrameTime;		updateThings();	drawThings();		lastFrameTime = System.currentTimeMillis();		try {		Thread.sleep(delay);	}catch(InterruptedException e) {}}


Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.