java - How to move a visible image diagonally? -
i have been trying figure out how make visible image move diagonally in applet window.
if press up, down, left, or right image (a gif) moves accordingly, if try press 2 keys @ once (up , right @ same time example) image moves in direction pressed second (even if press keys @ same time there still microscopic delay).
there might simple way fix not aware of, or perhaps workaround has figured out... appreciate or advice can given.
thank-you
hero class (this class defines "hero" is; in case simple pixel man, , can do)
import objectdraw.*; import java.awt.*; public class hero extends activeobject { private drawingcanvas canvas; private visibleimage player; public hero(location initlocation, image playerpic, drawingcanvas acanvas) { canvas = acanvas; player = new visibleimage(playerpic, canvas.getwidth()/3, canvas.getwidth()/3, canvas); start(); } public void run() { } public void move(double dx, double dy) { player.move(dx, dy); } }
herogame class (this class creates "hero" , specifies location, keys used make him move)
import objectdraw.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class herogame extends windowcontroller implements keylistener { private hero thehero; private image playerpic; private location initlocation; public void begin() { playerpic = getimage("player.gif"); canvas.addkeylistener ( ); this.addkeylistener ( ); requestfocusinwindow(); thehero = new hero(initlocation, playerpic, canvas); } public void keytyped( keyevent e ) { } public void keyreleased( keyevent e ) { } public void keypressed( keyevent e ) { if ( e.getkeycode() == keyevent.vk_up ) { thehero.move(0,-5); } else if ( e.getkeycode() == keyevent.vk_down ) { thehero.move(0,5); } else if ( e.getkeycode() == keyevent.vk_left ) { thehero.move(-5,0); } else if ( e.getkeycode() == keyevent.vk_right ) { thehero.move(5,0); } } }
thank-you once more taking time read , help.
this rather usual situation in games accept keyboard input. problem game needs act on all keys pressed far game concerned (meaning keys key_release event has not been fired yet).
keylistener
notify last key pressed (and keep notifying same key if hold pressed) need keep track of state rest of keys yourself.
to idea on how that, search keyboard polling (here example) popular technique don't act player's input rather store key presses in queue , later poll queue @ regular intervals (i.e. in game loop) decide keys pressed or not , act accordingly.
i hope helps
Comments
Post a Comment