Movement with timers.

i have a game in which my character moves when one of the direction keys is pressed.
when a key is pressed, a timer is created, along with a timertask the changes the characters location every couple of miliseconds depending on what direction is pressed.
when the key is released, the timertask and timers are cancelled.
the problem with this, is that the timer can malfuntion, causing the character to uncontrollably run away.
this is due (i theorize) to the timers adding up, when more than one key is pressed at the same time.
is there a better way to get the character to move? (rather than timers)
just pressing the key isnt an option, since there is a pause if you depress it for a couple of milliseconds before it starts running smoothly.

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.Timer;
public class KeyMotion
    public static void main(String[] args)
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new MotionPanel());
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
class MotionPanel extends JPanel
    Image image;
    int x, y, xInc, yInc;
    Timer upTimer, leftTimer, downTimer, rightTimer;
    public MotionPanel()
        x = 150;
        y = 150;
        xInc = 2;
        yInc = 2;
        loadImage();
        initializeTimers();
        registerKeys();
        setBackground(Color.white);
    protected void paintComponent(Graphics g)
        super.paintComponent(g);
        g.drawImage(image, x, y, this);
    private void registerKeys()
        String[] keys = { "UP", "LEFT", "DOWN", "RIGHT" };
        Action[] actions = { up, left, down, right };
        for(int j = 0; j < keys.length; j++)
            getInputMap().put(KeyStroke.getKeyStroke(keys[j]), keys[j]);
            getActionMap().put(keys[j], actions[j]);
    private void initializeTimers()
        upTimer = new Timer(40, new ActionListener()
            public void actionPerformed(ActionEvent e)
                y -= yInc;
                repaint();
        leftTimer = new Timer(40, new ActionListener()
            public void actionPerformed(ActionEvent e)
                x -= xInc;
                repaint();
        downTimer = new Timer(40, new ActionListener()
            public void actionPerformed(ActionEvent e)
                y += yInc;
                repaint();
        rightTimer = new Timer(40, new ActionListener()
            public void actionPerformed(ActionEvent e)
                x += xInc;
                repaint();
    private void loadImage()
        String fileName = "images/dukeWaveRed.gif";
        try
            URL url = getClass().getResource(fileName);
            image = ImageIO.read(url);
        catch(MalformedURLException mue)
            System.out.println("URL help: " + mue.getMessage());
        catch(IOException ioe)
            System.out.println("io help: " + ioe.getMessage());
    private Action up = new AbstractAction()
        public void actionPerformed(ActionEvent e)
            if(upTimer.isRunning())
                return;
            if(downTimer.isRunning())
                downTimer.stop();
                return;
            upTimer.start();
    private Action left = new AbstractAction()
        public void actionPerformed(ActionEvent e)
            if(leftTimer.isRunning())
                return;
            if(rightTimer.isRunning())
                rightTimer.stop();
                return;
            leftTimer.start();
    private Action down = new AbstractAction()
        public void actionPerformed(ActionEvent e)
            if(downTimer.isRunning())
                return;
            if(upTimer.isRunning())
                upTimer.stop();
                return;
            downTimer.start();
    private Action right = new AbstractAction()
        public void actionPerformed(ActionEvent e)
            if(rightTimer.isRunning())
                return;
            if(leftTimer.isRunning())
                leftTimer.stop();
                return;
            rightTimer.start();
}

Similar Messages

  • Movies with transparent backgrounds don't display in KN4

    In KN4, movies with transparent backgrounds (such as the countdown timers sold by KeynoteUser.com) no longer display when the show is presented. They clearly function when creating the slide, but not during presentation. I'm running the show on a MacBook Core Duo with 10.4.10 and GMA 950 graphics chips with 64 MB VRAM. This might be an issue with the GMA graphics chip although the movies worked perfectly with KN3 and earlier. Has anyone else observed this problem?

    The Keynote 4.0.1 update has fixed this problem. Thanks Apple!

  • Synching Movie with 30GB

    When trying to sync a movie i just downloaded the snyc began and a few seconds in a received the error message "Attempting to copy to the disk "Ipod" failed. THe disk could not be read from or written to"
    My first attempt was to try again, and the same error message appeared. I then went through the 5 r's and the problem still persisted.
    Next i went on to the troubleshooting topic and went through those fixes and used them. The only one i could not get to work was repairing the disk drive, and because i'm a windows user i had to use the chkdsk command and it did not work properly, or i did not format it properly.
    Anyway that still did not help and i went so far as to copy the movie file to a different folder, delete the original and then import it back in. Still the movie will not sync with the ipod. My best guess is the lack of USB 2.0 drives, in which case i would have to install a hub. But i would prefer another way out if possible. Any help would be appreciated
    Dell Dimension 4300   Windows XP   No 2.0 USB drives

    Hi
    May be You mean this ?
    Play all resp one chapter at a time
    Play All Button
    1. There are NO - Play All - button in any version of iDVD
    2. It can be faked in several ways
    • Easiest and most fault proof way is to make a doublet movie containing All and with
    Chapters set to match. It will take up x2 space but is easy to understand and produce.
    Cons: Tried this in iMovie’11 by Exporting out each part as a full Quality QT.mov then Importing back into new events and putting these into a new project (Play All project). Resulting DVD had Audio that was OK (as parts) - BUT the picture was very bad and standing photo were cut of in hight. So the Play All movie has to be created from same material and exactly in the same way as the individual parts + then Chapters has to be set to match.
    • It's said that one can put all movies into a Photo/SlideShow and this will also
    give the function of a Play All button - Tested - and ONE HAS TO un-cheque - Scale pictures to TV-Safe area else it will be a black frame all around and a small picture !
    Mike Evangelist1
    You might be able to get close to what you want by using a slideshow in iDVD. (It's not widely known, but you can put videos in a slideshow.) If you set the slide duration to manual, playback will pause after each movie/slide, and you can continue with the 'next' button.
    3. Using another program to do this e.g.. Roxio Toast™ where there is a Play All button option.
    Summary
    a. Making a Play All movie with same care as the individual Part movies - gives a very Good Result
    b. Using Roxio Toast™ - also an usable way to go
    Yours Bengt W

  • TS3772 I made a 3 minute movie with my iphone 4s. when I attempt to share it by message or email, a message says the movie is too long and that I must make clips. Is there any way to get around this and send the whole video? I think everything is in the c

    I made a 3-minute movie with my iphone 4S. When I attempt to share it via email or message I get a message that says it is too long, that I should try to make a clip. Of course I had rather send the whole thing. What are the possibilities? I think my music and likely my videos and pictures are in the cloud.

    SadisticIron wrote:
    i just baught my first iphone and it is a jalbroken
    Buzz! Thank you for playing!
    Discussing jailbroken devices is forbidden here by the Terms of Service.
    You can not get help here.

  • How do i connect my iMac to my tv to see movies with wire

    how do i connect my iMac to my tv to see movies with wire

    Hey rodskc10,
    Thanks for the question! Based on the iMac model and TV you have, you’ll need to pick up a compatible cable. There are a few options that can be found on the Apple Online Store:
    Mac Cables - Computer Audio & Video Adapters, Network Cables & More - Apple Store (U.S.)
    http://store.apple.com/us/mac/mac-accessories/cables#!
    For example, if you have the latest iMac and an HDTV, a mini DisplayPort to HDMI cable should do the job (you’ll connect this to the Thunderbolt port, which is backwards compatible with mini DisplayPort).
    For additional information, see this article:
    OS X Mavericks: Use a television as a display
    http://support.apple.com/kb/PH13801
    Thanks,
    Matt M.

  • When streaming a movie with the new Apple TV, and using a DSL Internet connection, all audio sound works, e.g., the music track, but the audio track with the actor's voices, does not work. What can I do?

    When streaming a movie with the new Apple TV, and using a DSL Internet connection, all audio sound works, e.g., the music track, but the audio track with the actor's voices, does not work. What can I do?

    Hi Brian,
    Thanks restoring and restarting didn't fix my problem - i have started it fresh and still it doesn't work. Basically I press ONCE on the remote, after the machine has not had any commands for 10 minutes, and the cursor skips from one end of the menu to the other - so I can't choose network or update software etc - I sometimes manage to stop it randomly in the middle of the menu if I press on a command in the middle of the cursor skipping all the menu steps...not sure what the problem is but I have basically not used my brand new apple tv since I bought it for that reason! I should call Apple support I suppose! grrrr hate wasting time with stuff like this!
    Thanks for your help though!
    Pernille

  • Flash movies with play button don't work

    I have the 'simple' problem that everytime I see a "play" button on a web page with flash content, clicking on it won't start the movie.  However, e.g. YouTube movies work fine. So it seems it's just movies that do not start automatically after clicking on a link.
    Also, checking the flash player e.g. at the Adobe site (http://helpx.adobe.com/flash-player/kb/find-version-flash-player.html), tells me in a flash box I have the latest flash player installed, and I see the  flash movie 'flash player is running on your system' with the red ball rolling in it.
    I have the same problem for both google Chrome and for IE.
    I still have an old Dell Inspiron 6000 notebook with Win XP (latest updates) and ATI mobility Radeon X300 graphics chip, for which I also installed the latest available drivers.
    Experimenting with Flash Player settings was unsuccessful so far (e.g. no hardware acceleration, clearing all internet data in the Flash Player global settings tool).
    My desktop (also with Win XP and with the same browsers and Flash Players/Flash Plugins installed works fine...).
    I also know that it worked at an earlier time with this NB...
    I managed to run the movie with a Linux Live CD but that is not what I want to do every time...
    Any idea is highly appreciated.....

    Hi BalusC, i have saved the datamodel (a ArrayList) in SessionBean. It can't be null. The rows of table display correct. I don't understand, why functions buttons with ObjectArrayDataProvider, but not with ObjectListDataProvider?
    I found a page with same problem: http://forum.java.sun.com/thread.jspa?threadID=549675&tstart=30

  • Can nolonger watch YouTube movies with my new Safari 2.0.4

    I recently went from an eMac with 10.3.9 - Jaguar, to an iMac with 10.4.8 Tiger. My Safari is 2.0.4.
    While I was able to watch all YouTube movies, I can nolonger do so. The movie stops about 5 seconds after watching a movie. It behaves as though I already watched the movie.
    I did a search to see if I could find similar incidents, and I can see that others may have experienced this problem, but no resolution was ever made.
    I run the disk utility almost daily, so there are no permissions that need repairing. I use Foxfire to watch the YouTube movies with no problem, so it appears to be a Safari thing. Not really a 'Safari' thing, more than a Safari 2.0.4 thing - at least it seems that way.
    Any help or advice would be appreciated. Thanks.

    Yes... that's what I meant! Actually, I cut and pasted that info, so I cut and pasted the wrong info!
    EIther way, it did answer my question, so I will mark it as such.
    I think that if the others who had the same problem who posted before me will be able to solve their problem as well.

  • How can I export/share a project/movie with iMovie 10(.0.1)?

    Hi,
    I generate a movie with images from iPhoto and underlaid a sound file. In iMovie the film looks great and now I want to share/export it. But the share button doesn't work: I click on it and nothing happens – no submenu, no window, nothing. It seems there is missing a function behind the menu item.
    I closed iMovie, restart it – nothing.
    I shut down the Mac and reboot it – nothing.
    I deleted the preferences after closing the app and restart it – nothing happens.
    What can I do?
    This happens with image movies AND with clip movies generated with iMovie.
    Thanks for a hint.
    CK

    Thanks Chris,
    I will uninstall the imovie app using the mackeeper uninstaller, but wanted to ask if I trash /delete all the files
    when I do this? When it scans my computer it says I have two versions of imovie and other files as well.
      Just wanted to check if I will still have my trailer left in my user file on the computer.
    Sorry to bug you, but I spent alot of time doing it and dont want to lose the work . So want to be sure I am doing it the right way!
    Cheers Graham

  • How to I share Itune library, and movies with a different user on the same computer?

    How do I share Itunes and movies with a different user on the same computer?

    https://discussions.apple.com/community/itunes

  • Getting error 8 during a file move with shortcuts

    Hello,
       I am using the file move vi to move files and shortcuts from one folder to another. This works file when I am trying to move files. but when I try to move a shortcut (a file with a extension of *.lnk) the move vi fails and gets a error 8 (permission error). Why is this happening? I am assuming that a shortcut is a file, so I am treating it as a file and therefore expecting the move vi to move the shortcut from one folder to another.
    Regards,
    Kaspar

    It could be that this is related to a bug that has already been discovered and reported. Our R&D deparment is working on it. When LabVIEW copies or moves a shortcut, it actually makes a copy of the file that is the target of the shortcut. However, it adds the ".lnk" extension to the end of the file name. This causes the new file to show up like a shortcut in Windows, but it is not a shortcut. If you rename the file and remove the ".lnk", then the file (the target of the original shortcut) will open without problem.
    One workaround it to use the System Exec VI to copy the file from the Windows command line. See the attached VIs.
    Jeremy P.
    Applications Engineer
    National Instruments
    Attachments:
    Move with Command Line for LNK.vi ‏16 KB
    Copy with Command Line for LNK.vi ‏36 KB

  • No audio streaming movies with iTunes 10.2.1 and iOS 4.3

    I upgrade to iTunes 10.2.1 and to iOS 4.3 and now I can´t listen audio on my movies with 6 channels audio. With two channels (stereo) there is no problem. With multichannel I just can see the video, but can´t listen. The problem is with my iPad and my Apple TV. On my iMac it works fine, I can see and listen.
    Anybody Help ??

    I have the similar problem with video. I can not stream movies to apple tv after ios 4.3 update that i used to stream before. The problem seems to be for some (but a lot) specific movies though. After going through all my videos i found a couple of videos that was able yo be streamed. Even with movies that can't be streamed the video loads (and even plays on fast forward but very slow without audio) but just pauses. It just loads opens and everything but just doesn't play.I don't have any problem with streaming audio from ipod or etc. I can still stream video from youtube as well but just can't do it from my itunes.
    Just to be specific, i have the issue with my ipad as well. The movies that i can stream to atv can be streamed to ipad as well (from my pc windows) but for other movies neither my atv nor ipad can play. A clear **** up by the developers. Just can't understand how they can release without even checking possible flaws.

  • Movie with english subtitles

    I'm an exchange student and I want to improve my english, but almost any movie in itunes has english subtitles (I do not want c.c.). Where can I rent or buy movies with subtitles.
    thanks

    I'm an exchange student and I want to improve my english, but almost any movie in itunes has english subtitles (I do not want c.c.). Where can I rent or buy movies with subtitles.
    thanks

  • Movie with special features won't play

    My sister sent me a movie that she purchased on her iTunes account and it sent completely to my iTunes.  It is a movie with extended features.  When I opened it in my iTunes it goes to a page that says "play", "chapters", "features", "more".  I am able to click features and more and it shows me those features however it asks me to authorize using my apple ID (even though it was purchased on my sisters).  When I go over to play movie or even chapters it will not let me play the movie at all and it does not even give me the option to authorize the movie.  She does not have 5 computers authorized on her account so there is no reason it should not work on my computer
    could anyone help with this problem?

    See:
    iTunes: May be unable to transfer videos to iPhone, iPad, or iPod
    iTunes: Frequently asked questions about viewing and syncing videos
    Try deleting and redownloading:
    Downloading past purchases from the App Store, iBookstore, and iTunes Store

  • Movie with Photo's

    I'm trying to make a movie with photo's and short video clips together. And then burn on a DVD, what is the easiest way to do this ?

    You'll need to go through the iMovie tutorials if you've never used the program before, but a quick start:
    Open iMovie, click on the little camera icon to the right and it will show your photos in iPhoto. Grab the photos you want and drag them over to the project window.
    The video files you've uploaded from your camera will be in the Event Library, which is below the project window. Click on any of those you want, and it will highlight a 4-second clip. Grab the ends of the box and drag them to get the footage you want -- then drag the clip to the project window.
    Rearrange them as desired. You can shorten or lengthen the duration of the photos.

Maybe you are looking for