Character in Java game not responding -
i have been following java game tutorials , go stuck on one, 1 here: http://www.youtube.com/watch?v=rolmrqekv3o&list=pl6e90696571998dc2 have issue character not respond arrow keys. if great. code:
package thejavahubgame; import java.awt.color; import java.awt.font; import java.awt.graphics; import java.awt.image; import java.awt.event.keyadapter; import java.awt.event.keyevent; import javax.swing.imageicon; import javax.swing.jframe; public class main extends jframe implements runnable{ int x, y, xdirection = 10, ydirection = 10; private image dbimage; private graphics dbg; image face; public void run(){ try{ while(true){ move(); thread.sleep(5); } } catch(exception e){ system.out.println("error"); } } font font = new font("arial", font.bold | font.italic, 15); public void move(){ x += xdirection; y += ydirection; if(x <= 0) x = 0; if (x >= 200) x = 200; if(y <= 50) y = 50; if(y >= 250) y = 250; } public void setxdirection(int xdir){ xdirection = xdir; } public void setydirection(int ydir){ ydirection = ydir; } public class al extends keyadapter{ public void keypressed(keyevent e){ int keycode = e.getkeycode(); if(keycode == e.vk_left){ setxdirection(-1); system.out.println("key pressed"); } if(keycode == e.vk_right){ setxdirection(+1); } if(keycode == e.vk_up){ setydirection(-1); } if(keycode == e.vk_down){ setydirection(+1); } } public void keyreleased(keyevent e){ int keycode = e.getkeycode(); if(keycode == e.vk_left){ setxdirection(0); system.out.println("key pressed"); } if(keycode == e.vk_right){ setxdirection(0); } if(keycode == e.vk_up){ setydirection(0); } if(keycode == e.vk_down){ setydirection(0); } } } public main(){ //load images imageicon = new imageicon("f:/android/workspace/thejavahubgame/src/thejavahubgame/face.gif"); face = i.getimage(); //game properties addkeylistener(new al()); settitle("java game"); setsize(250,250); setresizable(false); setvisible(true); setdefaultcloseoperation(exit_on_close); setbackground(color.green); x=150; y=150; } public void paint(graphics g){ dbimage = createimage(getwidth(), getheight()); dbg = dbimage.getgraphics(); paintcomponent(dbg); g.drawimage(dbimage,0,0, this); } public void paintcomponent(graphics g){ g.setfont(font); g.setcolor(color.magenta); g.drawstring("super-mega ball bouncer ii", 50, 50); g.setcolor(color.red); g.filloval(x, y, 15, 15); g.drawimage(face, x, y, this); repaint(); } public static void main(string[] args){ main jg = new main(); //threads thread t1 = new thread(); t1.start(); } }
thank you!
this may culprit:
main jg = new main(); //threads thread t1 = new thread(); t1.start();
you didn't pass runnable
thread
, thread isn't doing anything. without update thread, nothing in game move. try this:
main jg = new main(); //threads thread t1 = new thread(jg); t1.start();
Comments
Post a Comment