I'm trying to make the sprite speed-up gradually on button press and not to move constant speed only. Also set a max-speed limit. I hope you understand what i mean.
timer = new Timer(5, this);
timer.start();
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(image, x, y, this); //x,y = position
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
private class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -1;
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
}
}
}
public void actionPerformed(ActionEvent e) {
x += dx;
y += dy;
repaint();
}
You need to define and store the values for max speed, actual speed and the speed increment. The simplest way to define the speed increment, and should try it first, is to define a constant speed increment. Based on the provided code:
As I don't really know the context of the problem, or the goal to achieve, I didn't include any way to slow the sprite down again, once maxspeed is hit.
Some interval for speed gains may also be considered. With the above code, the updates to speed would be fast enough that you probably wouldn't notice them.
There are several things (initially) wrong with your example code...
paint
method. It is recommend that you override thepaintComponent
method instead. If you are overriding thepaint
method of a top level container, likeJFrame
, then it is recommended that you don't. Instead, use something likeJPanel
as the bases for your custom painting...Graphics
context that is past to you. This is VERY dangerous, as this will prevent anything else from been painted. TheGraphics
context is a shared resources, everything that needs to be updated during this repaint cycle will using the sameGraphics
context.KeyListener
.KeyListener
suffers from focus issues. This can easily be remedied through the use of the Key Binding API. Key bindings are also more flexible, as they separate the physical key from the action, allowing you to associate the action with different keys with little effort and/or reuse the underlying action (such as with buttons).So. For your question. You need to know...
You will also want to maintain the current position of the object you are altering.
This example doesn't actually move the "player" so much as it moves the background. The background position is altered by the
xDelta
, which is the speed of change...