Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Overall, the approach you're learning from your book is far from ideal for games but I touched up the code anyway. </p> <pre><code>import java.awt.*; import java.net.*; import java.awt.event.*; import java.awt.geom.*; import java.applet.*; public class DisplayImage extends Applet implements KeyListener{ int coordX=0;//ship x axis position int coordY=0;//ship y axis position /* 0-------------------------x 0| | | | | | y */ public URL getURL(String filename) { URL url = null; try { url = this.getClass().getResource(filename); } catch(Exception e){e.printStackTrace();} return url; } private Image image; public void init() { image = getImage(getURL("spaceship.png")); addKeyListener(this); } public void update(){repaint();}//let update control the calls to repaint public void paint(Graphics g) { Graphics2D g2d = (Graphics2D)g; g2d.setColor(Color.BLACK); g2d.fillRect(0,0,getSize().width,getSize().height); g2d.drawImage(image,coordX,coordY,this);//paint the spaceship to the updated coordinates } public void keyPressed(KeyEvent e) { int keycode = e.getKeyCode(); //37=left arrow. 39=right arrow. 38=up &amp; 40=down if(keycode==37){coordX-=1;}else if(keycode==39){coordX+=1;} if(keycode==38){coordY-=1;}else if(keycode==40){coordY+=1;} update();//request repaint when logic has updated } public void keyTyped(KeyEvent e){} public void keyReleased(KeyEvent e){} } </code></pre> <p>Cheers</p> <p>EDIT:: This is the basic concept you want to work on.</p> <pre><code>private void mainGameLoop(){ while(pause==false){ updateLogic();//process movement, detect collisions etc renderGraphics();//draw a new frame try{Thread.sleep(25);}catch(InterruptedException e){e.printStackTrace();}//sleep the thread to control the frame rate. (there are more efficient ways to sleep a thread but this is the most simplistic) } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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