Gradually speeding a sprite

后端 未结 2 2155
野性不改
野性不改 2020-12-11 14:19

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.

<
2条回答
  •  误落风尘
    2020-12-11 14:37

    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:

    int maxspeed = 5;
    int speed = 1;
    int acceleration = 1;
    
    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 = -acceleration;
            }
            if (key == KeyEvent.VK_RIGHT) {
                dx = acceleration;
            }
            if (key == KeyEvent.VK_UP) {
                dy = -acceleration;
            }
            if (key == KeyEvent.VK_DOWN) {
                dy = acceleration;
            }
        }
    }
    
    public void actionPerformed(ActionEvent e) {
        if (speed < maxspeed) {
            speed += acceleration;
        }
        x += dx * speed;   
        y += dy * speed;
        repaint();  
    }
    

    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.

提交回复
热议问题