rage
rage

Reputation: 1837

making object movement smooth in a java applet

Hi friends i'm trying to write a simple program that will move a little square right,left,up, and down smoothly.

As is, the square will indeed move in the four directions but there is a noticeable delay when trying to change the direction of the square. I plan on eventually writing a little game similar to the 'brick' game but in order to do that my object has to move smoothly. Can someone give me some advice on how to achieve this?

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;

public class FutureGame extends Applet implements KeyListener{

int deltax; 
int deltay;

public void init(){

    deltax = 0;
    deltay = 0;
    this.addKeyListener(this);
}

@Override
public void keyPressed(KeyEvent ke) {

    if(ke.getKeyCode() == ke.VK_RIGHT){
        deltax = deltax +10;
    }

    if(ke.getKeyCode() == ke.VK_LEFT){
        deltax = deltax - 10;
    }

    if(ke.getKeyCode() == ke.VK_UP){
        deltay = deltay - 10;
    }

    if(ke.getKeyCode() == ke.VK_DOWN){
        deltay = deltay +10;
    }
    this.repaint();
}
@Override
public void keyReleased(KeyEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void keyTyped(KeyEvent arg0) {
    // TODO Auto-generated method stub

}

public void paint(Graphics g){

    g.drawRect(deltax, deltay, 10, 10);
}

}

Upvotes: 0

Views: 2976

Answers (2)

huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11926

If your thread(games's main calculations) sleeping/waiting time is very small, your key-listeners could not catch your keystrokes within that small time. Make those thread waiting times bigger and try again. I mean the things in try-catch blocks.

You are drawing directly. Use buffering/doublebuffering.

Changing the buffer is much more faster than changing the contents of screen.

Upvotes: 1

java_xof
java_xof

Reputation: 439

First of all use paintComponent() as drawing method, then cast Graphics g to Graphics2D - make it more "Swingy", and last but not least follow the code as in java2s.com site java2s.com - Advanced Graphics - Smooth Moves

Upvotes: 0

Related Questions