Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>How can I smoothen the animation and still move fast?</p> </blockquote> <p>One technique is to paint semi-transparent versions of the moving object along the path it would have taken if stepping less pixels per move.</p> <p>E.G. for a 10 pixel move, draw a version at 10% opacity for the 1st pixel of moving, 20% for the 2nd etc.</p> <p><img src="https://i.stack.imgur.com/t7bJT.png" alt="Moving Block"></p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MovingBlock { MovingBlock() { final JPanel gui = new JPanel() { private static final long serialVersionUID = 1L; int x = 0; int step = 60; public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; x+=10; Color fg = getForeground(); for (int ii=x-step; ii&lt;x; ii+=4) { double transparency = (double)(x-ii)/(double)step; Color now = new Color( fg.getRed(), fg.getGreen(), fg.getBlue(), (int)(255*(1-transparency))); g2.setColor(now); g2.fillRect(ii, 3, 5, 10); } if (x&gt;getWidth()) { x=0; } } }; gui.setBackground(Color.BLACK); gui.setForeground(Color.GREEN.darker()); gui.setPreferredSize(new Dimension(400,16)); ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { gui.repaint(); } }; Timer timer = new Timer(20, listener); timer.start(); JFrame f = new JFrame("Moving Block"); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setContentPane(gui); f.pack(); f.setLocationByPlatform(true); f.setVisible(true); } public static void main(String[] args) throws Exception { SwingUtilities.invokeLater(new Runnable() { public void run() { new MovingBlock(); } }); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload