Player sprite just doesnt move smooth?

Hey guys, so I am developing my multiplayer game but I found out that my playe sprite while’st moving tends to get stuck sometimes… not flickering but rather just CPU context switch is really long & obvious, is this makes any sense…

so I made just a rectangle which you can move with keys but it is not smooth moving, sometimes IT seems like vsync decides to drop few frames(it’s just assumption, I dont know what exactly is going on…)

I have tried many high precision timers and different ways, here is the code:

here is my main window, taking care of sleeping and moving.



public class Main {

	public static void main(String[] args) {
		System.out.println("2D sprite test.");
		Window fx = new Window();
	    fx.g.createBufferStrategy(2);
		fx.g.buffer = fx.g.getBufferStrategy();
		long lastLoopTime = System.currentTimeMillis();
		int offset = 250;
		while(true)
		{
			long delta = System.currentTimeMillis() - lastLoopTime;
			lastLoopTime = System.currentTimeMillis();

			for(int i = 0; i < 4; i++){
				if(fx.g.keystates[i]){
					System.out.println("It is " + i);
					switch(i){
					case 0:
						// down
						fx.g.y += (delta * offset) / 1000;

						break;
					case 1:
						// left
						fx.g.x -= (delta * offset) / 1000;
						break;
					case 2:
						// up
						fx.g.y -= (delta * offset) / 1000;
						break;
					case 3:
						// right
						fx.g.x += (delta * offset) / 1000;
						break;
					}
				}
			}
	
			fx.g.draw();
			try{Thread.sleep(10);}catch(Exception e){}
		}
	}

}

MAIN.JAVA


import java.awt.Canvas;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;



public class GraphicsX extends Canvas implements KeyListener {
	public BufferedImage image;
	public BufferStrategy buffer;
	public boolean keystates[] = new boolean[4];
	public int x = 20, y = 20;
	public GraphicsX()
	{
		  GraphicsEnvironment ge = 
		        GraphicsEnvironment.getLocalGraphicsEnvironment();
		    GraphicsDevice gd = ge.getDefaultScreenDevice();
		    GraphicsConfiguration gc = gd.getDefaultConfiguration();
	    image =  gc.createCompatibleImage(400,  400);
	    setSize(500, 500);

	}
	//public void repaint() {}
	
	  public void draw()
	  {
		  Graphics g = buffer.getDrawGraphics();
		  g.setColor(Color.cyan);
		  g.fillRect(0, 0, 400, 400);
		    g.setColor(Color.red);
		    g.fillRect(x, y, 25, 25);
		    g.dispose();
		    buffer.show();

	  }
	  
		 public void keyPressed(KeyEvent e) 
		 {
			 keystates[e.getKeyCode() % 4] = true;
		 }

		 public void keyReleased(KeyEvent e)
		 { 
			 keystates[e.getKeyCode() % 4] = false;
		 }
		 public void keyTyped(KeyEvent e) {	}
}

GraphicsX.java


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;



public class Window extends JFrame
{
	public GraphicsX g;
	public Timer fpstimer;
	public Window()
	{
		super("lol");
		g = new GraphicsX();
		g.setIgnoreRepaint(true);
		g.setBackground(Color.cyan);
		g.setFocusable(true);
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().setBackground(Color.BLACK);
        setSize(600, 600);
        
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout());
        content.add(g, BorderLayout.NORTH);
        
        JButton hay = new JButton("LOL");
        content.add(hay, BorderLayout.SOUTH);
   
        g.addKeyListener(g);
        setContentPane(content);
        setVisible(true);
        
        // 

	    g.createBufferStrategy(2);
		g.buffer = g.getBufferStrategy();
	}

}

Window.java

Can anybody check out and see what could be possibly wrong or provide me code which renders really nicely and doesnt randomly ‘lag’…
I really suspect this might be the because of my Java version or maybe OS(Win7 64 bit) ???

Run with -verbose:gc and check whether the delays are at the same time as the GC.

Im not so sure how it helps you/me but here I run it:


Heap
 PSYoungGen      total 76480K, used 26487K [0x0000000015420000, 0x000000001a970000, 0x000000001a970000)
  eden space 65600K, 40% used [0x0000000015420000,0x0000000016dfde80,0x0000000019430000)
  from space 10880K, 0% used [0x0000000019ed0000,0x0000000019ed0000,0x000000001a970000)
  to   space 10880K, 0% used [0x0000000019430000,0x0000000019430000,0x0000000019ed0000)
 PSOldGen        total 174784K, used 0K [0x000000000a970000, 0x0000000015420000, 0x0000000015420000)
  object space 174784K, 0% used [0x000000000a970000,0x000000000a970000,0x0000000015420000)
 PSPermGen       total 21248K, used 8773K [0x0000000005570000, 0x0000000006a30000, 0x000000000a970000)
  object space 21248K, 41% used [0x0000000005570000,0x0000000005e01750,0x0000000006a30000)

I couldnt make it display with dates tho, seems like date option doesnt exist in new VM or is placed with something new :\

also I tried few others game which are in internet(Space inwaders for example) and they all seem to have same problem as me.
So I tried with my other computer(has vsync disabled) and it had exactly the same problem…so Im just thinking that java doesnt suit my needs for player movement, I think it is inevitable and every java game has it, it does not affect playing game but it sure does annoy my eye… :-\

I also used VM flags to make my heap 512 mb by default, my program used 20mb so I dont think the GC was problem anyways…
it just seems that the faster player moves, the more obvious the random jittering is…the few games I played were pretty okish, I could definitely see the jittering but it wasnt that annoying.(althought characters in those games were moving slower by like 35% or so.)

I think this is why they say that Java isnt the best option for game development… works well for simple games such as card games, I havent yet chance to get look at java3D library but it sounds like it is programmed using native libraries(C or so)…

I feel the same problem, a small unidentifiable hitch now and then, but i dont see it in puppygames games… hmmm. Theres must be a trick hidden somewhere.
Perhaps as riven suggested, with the debug console open, does the gc spout material during the hitches? I havent yet tried this being busy with another project but will definitely investigate more, as i presume android games will have similar gc processes behind the scenes. Perhaps the answer is to make sure we are not allocating/deallocating anything during gameplay?
I refuse to believe Java should just be ditched as unsuitable for gaming on a feeling, hard data is needed… As another thread, showed, there are starting to be over a dozen marketquality games made in Java, and they have gotten around these hitches surely.

I experience the same problem in all of my games. I don’t think it is due to GC pauses because once in fullscreen exclusive mode, everything runs smooth. I’m still hoping for a Java update that magically eliminates that problem. Hoping for many years now…

nice, I was under the impression that full screen would work better(i dont know why but just had feeling lol), I shall try it soon and tell how it goes.
thanks

I tested your games hansdampf and couldnt get a glitch for 10-15 minutes ( quite good stuff too) …but it’s not fullscreen mode, so the magic is/isnt in the full screen exclusive mode?

I’ve never had anything but bad experiences with Java2D.

I have never had any issues like this when using LWJGL (which PuppyGames uses also). In general if you want good graphics performance you’ll want to switch to OpenGL. If you want good performance without having to sign your JAR, try out PulpCore, I’ve only seen beautiful stuff from it.

The problem is very obvious in my game ‘CaveCopter’, a sider-scroller. The Applet version has framedrops from time to time. There is a Webstart link below the Applet and you can go fullscreen with F11 -> runs very smooth for me. You can press F2 to see the uncapped fps. I have around 130 fps, so there should be lots of time left, but the Applet version is still jerky.

I want to live in your world, Demonpants.
I remember there was a guy defending C over Java here on this forum and asking for a simple loop to animate a moving rectangle SMOOTHLY. There was nobody here on this forum who could deliver such a loop with plain java2D and non-fullscreen. The praised Pulpcore is great, but it suffers from the same problem. Just try the
http://www.interactivepulp.com/pulpcore/tilemap/ demo. I can see glitches. I remember (90% sure) a version of that tilemap demo with the possibility of scrolling with cursor keys, when the glitches were more obvious. Now it is hard to detect because the movement is so quick.

edit: sorry Demonpants, I didn’t read your first sentence correctly (just woke up), now that makes sense :slight_smile:

Yeah the problem is actually that Java2D has no way to sync to screen refreshes. It does sync in full screen mode by doing page flipping, depending on your hardware i think. There’s a discussion and a bug for it here:
http://www.java-gaming.org/index.php/topic,14696.0.html
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6378181

Pulpcore uses Java2D under the hood to render without permissions.

Applets are slow on vista since hw-acceleration is disabled due to some windows bug:
http://www.java-gaming.org/index.php/topic,21468.0.html
Do you see a lower FPS on the applet version? With a lower FPS the screen tear would be more obvious I guess so it would look worse? With full screen mode there should be no screen tear since Java2D would use page-flipping, and should v-sync to the screen’s refresh rate.

I’m sure you know this but another way to render a smooth rectangle and cover up the screen-tearing is to use motion blur, but that’s a sub-par solution…

Keith 8)

PS: with just 15 more votes that bug (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6378181) would be in the top 25 bugs. Come on guys vote it up!!

Can’t help but to see you’re using int for your positioning/offsetting. I’d recommend float for a more smooth movement.

SmoothScrolling!

I have boardgames and clickclick site on a build, i only use Java2D with my project,
i have quite a smooth game play, i use following on my “render” loop.


if ( -- this.gamesurface_sync_delay < 1 )
{
	Toolkit.getDefaultToolkit ( ).sync ( ) ;
	this.gamesurface_sync_delay = 4 ;
}

My games on a build are found here -> http://temp4322.dy.fi

There may be some slowdowns at start on windows machines, but with linux it is quite a smooth all the way.
you may should choose the “Q” key for Air Pilots 1917 to see the best and smoothest for purpose, it is still to set only for 25 fps.

( Edit. I also use scale for smooth movement, 1500-15000 pixels applet height, and 4:3 or 16:10, seems to be enough for me. )

( Edit2. I also have here my Caveflyer demo from 2007, it is quite a smooth too, even if it is not smooth at all, when game situtations
change fast game may look smooth, even if not -> http://temp4322.dy.fi/JavaGame001/dist/launch.jnlp

//…

Thanks…

@Peasley :

your mainloop does not seems right for me especially

try{Thread.sleep(10);}catch(Exception e){}

Thread.sleep can vary a lot between OS and even different call in the same program

maybe you could try something like that


interval=40; 
lastDraw=0;
while(running)
{
 while(System.currentTimeMillis()-lastDraw<interval)
	Thread.sleep(1);
 
 lastDraw=System.currentTimeMillis();
 this.draw();
 
}

the stuttering is obvious with this demo http://www.interactivepulp.com/pulpcore/pathmotion/

This bug should be in the top 25 now (it hast 43 votes, minimum is 42), let’s vote it up to the top

You’re right! woot, and I bet that when it gets up there more people will vote it up even higher

Since this problem still persists with JDK7 b129, I just voted for this to be fixed.
Whoever hasn’t voted, should.

[quote]There’s a discussion and a bug for it here:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6378181
This bug should be in the top 25 now (it hast 43 votes, minimum is 42),
let’s vote it up to the top
[/quote]
OMG, it looks like this bug has disappeared from the bug database …

Last week I tried to vote for this bug, but the voting-process
looked broken then, the site was real sloooow and nothing happend
when voting.
Now I was attempting to try again, but the bug is no longer there …
(The site says ‘This bug is not available’).

Does anyone remember the title or the keywords for this bug,
so we can search the bug database for it ?

Never mind, the bug is back in the bug database.

I’m attempting to vote, but the site is, again,
real sloooow, so I guess it will not succeed this
time either … (already waiting more than 10 minutes
after clicking ‘vote’ …) :frowning:

I always wondered why those bugs get so few votes,
the bugs in the top 25 only have around 250 votes or so,
but I think now I know why that is … >:(

I have 10 game that run smooth on Android, J2ME/BlackBerry, and J2SE. It is not a bug. It is the code and it is not a secret.

After a game is fully loaded the game play should be smooth.

The issues are performance related usually to threading or long running code per frame or paint. I promise. I get clean steady 60 fps on 59 dollar phones.