Move sprite using keyboard

Hi. I am trying to make a simple game where you move a tank around. My problem is that I can't seem to get it to move right.
Here is the code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
public class JavaGame extends Applet implements KeyListener{
  private Image martin;
  Point pos = new Point(200,200);
  double angle = 0.00;
  double vel = 0;
  public void init() {
    setBackground(Color.white);
    addKeyListener(this);
    martin = getImage(getDocumentBase(),"tank.gif");
  public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
             AffineTransform tx = new AffineTransform();
             double scalex = 1;
             double scaley = 1;
             tx.scale(scalex, scaley);
             double x = pos.x;
             double y = pos.y;
             double dx = Math.sin(angle)*vel;
             double dy = -Math.cos(angle)*vel;
             pos.x+=dx;
             pos.y+=dy;
             tx.translate(pos.x, pos.y);
             tx.rotate(angle,16,16);
            g2d.drawImage(martin, tx, this);
  public void keyPressed(KeyEvent e) {
      if (e.getKeyCode() == KeyEvent.VK_UP)   vel = 2;
      else if (e.getKeyCode() == KeyEvent.VK_DOWN) vel = -2;
      else if (e.getKeyCode() == KeyEvent.VK_LEFT) angle -= 0.02;
      else if (e.getKeyCode() == KeyEvent.VK_RIGHT) angle += 0.02;
      repaint();
  public void keyReleased(KeyEvent e) {}
  public void keyTyped(KeyEvent e)    {}
}Any help appreciated

Hehe... Sounds simple enough. I could do that if I could understand why my sprites rotate angle changes after driving forward or backward (see the example at http://www.harme.dk/tank). When the "game" starts and you press left or right, the tank rotates correct, but after you push up, and move the tank, the rotate doesn't work anymore.
I would think it have something to do with either my math, or the transform method?

Similar Messages

  • Lost ability to move clips using keyboard -and fix

    So suddenly the other day, I could no longer move clips in a timeline using the keyboard. I would select a clip in the timeline and hit (for example) +40 to move the clip down the timeline 40 frames. Didn't matter whether I used the numeric keypad or the keys on the main part of the keyboard. Didn't get any error message or beep. When I hit the plus (or minus key) the little move window would open, I would enter numbers and hit either enter or return. And nothing would happen. I could click and drag on a clip in the timeline without any problems.
    I tried deleting preferences but it didn't help.
    Solution: created new sequence, and copied the contents of the problem sequence to the new sequence and problem solved.

    Thanks for the post Michael.
    I'm curious, you didn't by any chance move up to QT 7.6 did you?

  • Movieclip.x movement using keyboard event

    Hi, im working on a game project and i have a question about movie clip movement using keyboard event.
    Basicly i have a character on screen and it can move on the x axis using the left and right buttons.
    Im making my charater move by changing the x value of the character movieclip but i find very it laggy and not smooth and if im going point by point
    then it's too slow.
    Whats the best way to make the character move so that the transition will be smooth.

    Ok obviously you've left out where you add your eventListener, i'll assume that's a KEY_DOWN event. When the user holds down a key, that key event is triggered once immediately and then after a pause it is triggered at regular intervals. Check this out by holding down the up/down arrow and watching this browser window scroll.
    That's not the movement you'd be looking for when moving a character in a game. Instead, you'd be setting a variable on KEY_DOWN to indicate the character direction - it could be an integer for example that you increase by 1 if the user pressed RIGHT or decrease by 1 if the user pressed LEFT.
    In addition to your KEY_DOWN eventListener, you could have an ENTER_FRAME and  KEY_UP eventListeners set up:
    The enterFrame event handler could move the character in the direction specified in your direction variable. This is where you might ensure your character doesn't go beyond its limits in both directions.
    In the keyUp event handler, you could do the converse of what you did in the keyDown handler(increase by 1 if the user released LEFT, decrease by 1 if the user released RIGHT).

  • Using keyboard commands to move an object

    Hello, I am trying to make a quasi-asteroids program. I'm trying to move a ship around using keyboard commands. If I put the keyboard commands in the same class as the ship it does fine. Now I'm trying to put all the keyboard commands in their own class. This is where I am starting to have trouble. Here's the code for the commands class and ship class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Ship implements KeyListener
         ImageIcon ship;
         final int WIDTH = 300;
         final int HEIGHT = 225;     
         final int JUMP = 5;
         private int     x,y;          
         private int iWidth, iHeight;
         public boolean movingLeft,movingRight,movingUp,movingDown;
         public Ship ()
              ship = new ImageIcon ("ship.gif");
              iWidth = ship.getIconWidth();
              iHeight = ship.getIconHeight();
              x = WIDTH/2-10;
              y = HEIGHT/2;
         public void move ()
              if (movingLeft)
                   x -= JUMP;
              if (movingRight)
                   x += JUMP;
              if (movingUp)
                   y -= JUMP;
              if (movingDown)
                   y += JUMP;
         public void draw (Graphics page)
              page.drawImage (ship.getImage(),x,y,null);
    import java.awt.*;
    import java.awt.event.*;
    public class DirectionListener implements KeyListener
         private Ship s1;
         public DirectionListener ()
              s1 = new Ship ();
         public void keyPressed (KeyEvent event)
              switch (event.getKeyCode())
                   case KeyEvent.VK_DOWN:
                        s1.movingDown=true;
                        break;
                   case KeyEvent.VK_UP:
                        s1.movingUp=true;
                        break;
                   case KeyEvent.VK_LEFT:
                        s1.movingLeft=true;
                        break;
                   case KeyEvent.VK_RIGHT:
                        s1.movingRight=true;
                        break;
         public void keyReleased (KeyEvent event)
              switch (event.getKeyCode())
                   case KeyEvent.VK_DOWN:
                        s1.movingDown=false;
                        break;
                   case KeyEvent.VK_UP:
                        s1.movingUp=false;
                        break;
                   case KeyEvent.VK_LEFT:
                        s1.movingLeft=false;
                        break;
                   case KeyEvent.VK_RIGHT:
                        s1.movingRight=false;
                        break;
         public void keyTyped (KeyEvent event) {}
    The problem is obviously trying to communicate between the classes. Why can I not assign the boolean variables in the Ship class from the DirectionListener class? Thanks in advance.

    A program is worth a thousand words, er a ... well whatever ...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Ship extends JFrame {
      ImageIcon ship;
      final int WIDTH = 300;
      final int HEIGHT = 225;
      final int JUMP = 5;
      private int x,y;
      private int iWidth, iHeight;
      private boolean movingLeft,movingRight,movingUp,movingDown;
      public Ship() {
        ship = new ImageIcon ("ship.gif");
        iWidth = ship.getIconWidth();
        iHeight = ship.getIconHeight();
        x = WIDTH/2-10;
        y = HEIGHT/2;
        this.getContentPane().addKeyListener( new DirectionListener() );
        // You'd add the DirectionListener to whatever component you want.
      public void move() {
        if (movingLeft)  x -= JUMP;
        if (movingRight) x += JUMP;
        if (movingUp)    y -= JUMP;
        if (movingDown)  y += JUMP;
      public void draw (Graphics page) {
        page.drawImage (ship.getImage(),x,y,null);
      class DirectionListener implements KeyListener {
        public DirectionListener() {
        public void keyPressed(KeyEvent event) {
          switch (event.getKeyCode()) {
            case KeyEvent.VK_DOWN:
              movingDown=true;
              break;
            case KeyEvent.VK_UP:
              movingUp=true;
              break;
            case KeyEvent.VK_LEFT:
              movingLeft=true;
              break;
            case KeyEvent.VK_RIGHT:
              movingRight=true;
              break;
            default: break;
        public void keyReleased(KeyEvent event) {
          switch (event.getKeyCode()) {
            case KeyEvent.VK_DOWN:
              movingDown=false;
              break;
            case KeyEvent.VK_UP:
              movingUp=false;
              break;
            case KeyEvent.VK_LEFT:
              movingLeft=false;
              break;
            case KeyEvent.VK_RIGHT:
              movingRight=false;
              break;
            default: break;
        public void keyTyped(KeyEvent event) {
      public static void main(String[] argv) {
        new Ship();
    }... I made it an inner class, because you want to do very program specific stuff. I don't know really if I like this approach either, but I can't see what else you'd mean to do with the code you posted, what with the DirectionListener class doing such specific kinds of things.
    Some general critique: You forgot to add the 'default' keyword to your switch statements; and you really don't want to make the booleans public.
    ~Bill

  • Why is it so hard to just use Keyboard controls to navigate Finder?

    In pre OS X days I and my co-workers would use only keyboard shortcuts to navigate file servers faster than the network could even refresh the display just using Command keys and Tab and letters…
    In Finder if I want to move to the shortcuts side-bar (the way you can in an Open dialogue box with Tab) it seems to require cursor action, and since I use a tablet that means moving RH away from keyboard and gripping pen, which we all seem to hold between thumb and palm.
    If I hit Tab with a Finder window active, I get the current directory of files and I can manually move thorugh Cmd-Sft-D for desktop and then drill down etc etc  I also find it can be really hard to make a window or floating pallete the active window, and even when it is, impossible to highlight the correct field/content just using Keyboard shortcuts. I'm finding hard to beleive I not missing something, this being Apples OS and Apple have had unviersal access for a few decades!

    Hmmm, if these are commonly used Folders, try dagging them to the right side of the Dock between Applications & trash.

  • How do I move the alphabet keyboard on my iphone 5 iOS 8?  It is stuck on my DropBox app., I can't slide the keyboard down.

    As I open my DropBox App the keybioard appears adn prevents me from entering my password to access my DropBox content.  How do I move the alphabet keyboard on my iphone 5 iOS 8?  It is stuck on my DropBox app and I can't slide the keyboard down.

    Well, as an AT&T user, APN settings are governed by the carrier file, and we cannot change them. I've not used the configuration utility, so I'm "dumber" than you! See if this support document will help you out any. http://support.apple.com/kb/HT4839.

  • Page up and down without using keyboard

    can any body tell me, how can I write the code for page up and page down in alv grid report without using keyboard.I have make a report(showing in alv grid formate) and I am using menu printer(se41) and gave P,P+,P-,P-- in function key.
    and call this function in report using pf-status. but i didnot get the result without keyboard.while using keyboard page up and page down it is working fine.

    Hi Rakesh,
                    This is the code for ur problem check it once.We have to use this code according to ur requirement ok..The compulsory condition is data is present in the internal table not in database table.If it is in database table move it to internal table first.And follow the below logic that will work fine 4 ur problem check it once.
    *Local Variables
      DATA: lv_temp  LIKE sy-tabix.
    CASE sy-ucomm.
    *Fetch the FIRST Line from the Internal Table.
        WHEN 'FIRS'.
          READ TABLE gt_data INTO wa INDEX 1.
          lv_temp = sy-tabix.
    *Fetch the NEXT Line from the Internal Table.
        WHEN 'NEXT'.
          lv_temp = lv_temp + 1.
          READ TABLE gt_data INTO wa INDEX lv_temp.
    *Fetch the PREVIOUS Line from the Internal Table.
        WHEN 'PREV'.
          lv_temp = lv_temp - 1.
          READ TABLE gt_data INTO wa INDEX lv_temp.
    *Fetch the LAST Line from the Internal Table.
        WHEN 'LAST'.
          READ TABLE gt_data INTO wa INDEX sy-tfill.
          lv_temp = sy-tfill.
    Award points if helpful.
    Kiran Kumar.G.A
                     Have a Nice Day..

  • How to switch frames using keyboard

    Hi,
    I'm new to Actionscript. Now using Actionscript 3.0
    I have to switch next or previous frame in timeline using
    keyboard. I wrote
    ======================================================================================
    stage.addEventListener(KeyboardEvent.KEY_DOWN, goTimeline);
    function goTimeline(event:KeyboardEvent):void
    nextFrame();
    ======================================================================================
    How can I assign arrow keys to switch frames...
    Regards,
    Shaji T.U

    Here's a simple class that moves a circle with the key
    arrows...
    Take a look at how it works and edit it so it suits your
    needs.
    Good luck.

  • Best way to move sprites around in the scene?

    What is the best way to move sprites around on the scene?
    So far I came up with this code to move all the sprites from the right to the left
    var anim = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames: KeyFrame {
    time: 0.1s;
    action : function(){
    for(n in container.content){
    def item = n as Sprite;
    item.posX -= 2;
    it moves the sprites for 2px every 0.1s, but it's not so smoth.
    Is there a better way for doing it?

    netsuvi wrote:
    But this approach limits me in someway that i am unable to change yet. It means that I have to know
    the end position on the sprite at the beginning? But how about user interaction? I would like to adjust the speed, during running.
    Or how about collision detections?To use this technique, you have to know the end position, at least provisionally, at the start.
    If something changes during the timeline (such as the user clicking) you can always stop the timeline
    and recompute a new trajectory and start another timeline.
    Collision detection is harder, especially among objects that are all moving.
    I saw some people are just generation tics. Like 10 per seconds, Then then calculate the whole stuff in a function.
    probably it would be enough to have 2 calculation tics per second and let the javaFX engine calculate the necessary frames in between.This is a reasonable approach, and it's fairly straightforward. However, even in some cases like BrickBreaker, you can compute
    the endpoint or do collision detection (mostly) up front without having to compute frame-by-frame. For example, when the ball
    is heading up, you can tell from its position and velocity whether it's going to hit a brick or a wall and when it will hit. When the
    ball is heading down, you don't know whether the ball will hit the paddle, because the user can move it. However, the paddle
    moves only horizontally along a certain Y-position, so you can compute the time and location at which the ball will reach that
    Y-position. If the paddle is there, it bounces, otherwise the ball drops off the bottom and the turn ends.
    If you want to compute collision detection among two or more moving objects, well, that's a lot harder. It probably requires doing
    a bunch of math, and it might be possible to do in closed form. If not, successive approximation might be the easiest way to do
    it.
    So in pseudo code it would something like this:
    Animation Start 0Seconds: Sprites have this position
    Animation Start 0.5Seconds: Move sprite to this position // JavaFX makes the in between steps
    do function() {
    calculate speed,
    calculate collision detection or whatever
    then restart the Animation steps.I think the key is to decouple the position and collision computations from the actual graphics animation.
    For example, suppose you have an object heading towards a wall that's 500 pixels away, and it's moving at 250
    pixels/sec. (Assume constant velocity.) Then you know that the object will be at the wall in 2 seconds, so
    you just set up a KeyFrame with that information, put it into a Timeline, and run it. You'll need to put an action
    function in the KeyFrame as well. But note that this doesn't necessarily compute the next 0.5 seconds or the
    next 2 seconds. Instead, it should look at the new state and compute the time at which the next event occurs
    and then set up KeyFrames to run all the objects until that time.
    I tried something with the timeline.playFromStart() but it didn't work. It just repeated the same animation instead of doing a new one.
    You have any clue how to do that?The playFromStart() function will simply replay the same animation, as you noted. What you want to do is
    recompute KeyFrames starting from the current state that show animation to some future state. Then,
    load these KeyFrames into the Timeline (or create a new Timeline) and run it.

  • Goods Receipt Report With 101 movement type using bapi_goodsmvt_create

    Dear Abapers,
            i am getting some problem, i got requirement like Goods Receipt Report with 101 movement type using
    bapi_goodsmvt_create and data should upload through excel sheet.
    still facing problems, i have searched sdn forum n sdn code also, but relevant answer i could not find.
    What are all the inputs i need to take and please give some valuable inputs to me.
    please do help ..... thanks for advance..
    Thanks & regards,
    Vinay.
    Moderator message : Spec dumping is not allowed, show the work you have already done. Thead locked.
    Edited by: Vinod Kumar on Sep 27, 2011 10:58 AM

    Dear Abapers,
            i am getting some problem, i got requirement like Goods Receipt Report with 101 movement type using
    bapi_goodsmvt_create and data should upload through excel sheet.
    still facing problems, i have searched sdn forum n sdn code also, but relevant answer i could not find.
    What are all the inputs i need to take and please give some valuable inputs to me.
    please do help ..... thanks for advance..
    Thanks & regards,
    Vinay.
    Moderator message : Spec dumping is not allowed, show the work you have already done. Thead locked.
    Edited by: Vinod Kumar on Sep 27, 2011 10:58 AM

  • Using Keyboard keys in Fields setting in Crystal Report Design ?

    Hi Experts
    I want to know that how can I change text object or a field size or position by keyboard. sometimes it works and sometimes not. What is the setting for using keyboard.
    Thanks
    Regards
    Gorge

    Keyboard keys will only work under certain modes in CR.  You have to check the mode constantly to see in which ways they work.  There are too many conditions may cause them not work.  That list could be too long to find them all.  You would have a good grasp on the rule after you familiar with them.
    Thanks,
    Gordon

  • My keyboard on macbook pro (laptop) is acting weird. One key is not responding at all. Have verified using Keyboard viewer and some other keys are printing the unresponsive character at random.

    my keyboard on macbook pro (laptop) is acting weird. One key is not responding at all. Have verified using Keyboard viewer and some other keys are printing the unresponsive character at random. "z" is the unresponsive character.
    Is it a damaged keyboard ?
    The laptop is just 2 months old, will Apple replace it with a new one if its indeed a damaged keyboard or just repair, I use it for official purposes so being without a laptop is not much of an option.

    No one here works for Apple, so we don't know what Apple might or might not do.  If it's a genuine defect, they will of course repair it under warranty.  It is not their responsibility if it effects your ability to work or not, so that's on you.
    If, however, they determine that the key is problematic as a result of your misuse of the laptop, then everything is on you.  And trust me, if they find a glob of dried up beer or coffee there, they will charge you.
    Your only choice is to take it in for repair.

  • I am Unable to Type or use Keyboard in Firefox 18.0 anywhere including URL bar and Search Bar. how should rectify this?

    I am unable to type anything or use keyboard to type in Firefox. I am using Firefox 18.0 installed on Windows 7.
    I am able to Paste into the URL bar and also the Search bar but absolutely not able to type in it.
    I have already tried the "reset" option but still unable to type.
    Also tried Firefox in safe mode with disabled addons but still unable to type.
    Installed a fresh copy of firefox after uninstalling Firefox and deleting the old folder "Mozilla Firefox" from windows. but still unable to type.
    Please tell me a solution to this.

    I'm not on a laptop so I don't have a FN key. But on my desktop F9 + Windows key appears to have resolved the issue for me. Thanks for the help!

  • Sharepoint 2013 copy/move operation using Content and Structure fails

    Hi,
    We had a recent upgrade from SP2010 to SP2013 environment. After the migration, we realized that the
    copy/move operations using Manage content and structure(sitemanager.aspx) is not working as expected, neither does this give any error nor is it stuck. In fact if I check the content and structure log I find the message as
    succeeded but file/item is not copied to the target. 
    The strange thing is that if I am performing this operation with Full Control permission level it
    does not work but if I do the operation as Site collection admin it works without problem. I know if sub-sites are to moved then one should be site col admin but in this case I am trying to move just documents or pages.
    Any help will be greatly appreciated.
    Thanks

    Hi Vineet,
    According to your description, my understanding is that copy/move operation using Content and Structure cannot work in SharePoint.
    I recommend to check if there are any custom fields in the source list/library and target list/library. If yes, delete the custom fields to see if the issue still occurs.
    Here is a similar thread for you to take a look:
    http://social.technet.microsoft.com/Forums/en-US/56d803d7-8573-4c29-9f6b-c63023941f44/manage-content-and-structure-cannot-move-or-copy-items?forum=sharepointgeneralprevious
    To copy or move files/items between sites, we need to have
    appropriate permissions on both sites.
    I recommend to check if the user has full control on both sites.
    Best regards.
    Thanks
    Victoria Xia
    TechNet Community Support

  • How to create Contract or Move-in using Function module

    Hello Gurus,
    I'm looking for a way to create contract(Move-in) using Function module.
    Please help me out...
    Thanks in advance,
    Rajesh

    Hi Rajesh,
    Please try this: BAPI_ISUMOVEIN_CREATEFROMDATA
    Regards,
    S

Maybe you are looking for

  • Connect MacBook Pro with Mini DisplayPort to TV?

    I have a 15" MacBook Pro with the Mini DisplayPort outlet. I used to have a PowerBook which I was able to connect to my TV via the video adapter. No such adapter is included with my MacBook. How can I connect it to my TV to view videos, movies, tv sh

  • Error "unable to start correctly" for LR4

    I just installed LR4 on a new laptop running Win 8.  I get the following error when I try to start LR4 "unable to start correctly (0xc000007b)"  I have restarted the laptop after the install. Any suggestions on how to resolve this issue. 

  • Income statement report base on location..

    Hi Experts, Are there ways to configure SAP that it will be able to Generate FS report base on location? are fields available for this requirement? Much thanks, Jose mari Dres

  • How to park the invoice using 'IDOC_INPUT_INVOIC_MRM' ....

    Hi All, I am using FM 'IDOC_INPUT_INVOIC_MRM' for parking the incoming (Idoc) invoices. But FM   IDOC_INPUT_INVOIC_MRM   directly posts the invoices. I think is by default from SAP.(not sure) Can you Pls help me on this issue. Thanks.

  • How do I get JDeveloper to recognize subversion

    I checked out a project from subversion using TortoiseSVN. When I opened the project in JDeveloper it did not recognize that it was under subversion control. How do I make JDeveloper aware that the project is under subversion control? And before you