java - when using the arrow keys my image disappears -
the problem when press down button, image (blueboy) disappears, , doesn't move can move side side, cant understand why? please help. (i'm using realj). if there website can me on 2d side scrolling games me well.
import java.applet.applet; import java.awt.event.*; import java.awt.*; public class projectblue extends applet implements actionlistener,keylistener,mouselistener { image blueboy,trees; //image variable int size = 4,jump = 50, cx = 1, cy = 1; public void init() { blueboy = getimage(getdocumentbase(),"png.png"); trees= getimage(getdocumentbase(),"background.jpg"); addkeylistener( ); addmouselistener( ); } public void paint(graphics g) { int width = trees.getwidth(this); int height = trees.getheight(this); //system.out.println("" + cx +","+ cy); //the later images drawn on top of earlier ones. g.drawimage(trees, 1 ,1, width*size,height*7,this); g.drawimage(blueboy, cx, cy, this); } public void actionperformed(actionevent e) { repaint(); } public void left(){ cx = cx -100; // blueboy moves left } public void keytyped(keyevent e) { } public void keypressed(keyevent e) { system.out.println("key pressed"); int key = e.getkeycode(); if (key == keyevent.vk_left) { left(); } if (key == keyevent.vk_right) { cx = cx + 100; //blueboy moves right } if (key == keyevent.vk_up) { while (cy >= 0 && cy <=1000) cy = cy - 100; if (cy < 0){ cy = 1; //blueboy moves up, if goes out of bounds goes top } } if (key == keyevent.vk_down) { while (cy >= 0 && cy <=1000) cy = cy + 100; if (cy > 1001){ cy = 999; } //blueboy moves down, if goes out of bounds goes bottim } repaint(); } public void keyreleased(keyevent e) { } public void mouseentered( mouseevent e ) { } public void mouseexited( mouseevent e ) { } public void mousepressed( mouseevent e ) { } public void mousereleased( mouseevent e ) { } public void mouseclicked( mouseevent e ) { int x = getx(); int y = gety(); system.out.println("clicked @ (" + x + ", " + y + ")"); } }
those while loops tie gui thread, rendering animation useless. shouldn't if blocks instead? also, should enclose all blocks in curly braces. indentation lying you, , braces show why.
also need call super.paint(g)
method in paint override.
also, assignment, , if required code awt/applets , not swing?
Comments
Post a Comment