Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Problem in rotating and moving image at the same time

  1. #1
    Junior Member
    Join Date
    Jun 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Problem in rotating and moving image at the same time

    hello every one hope fine
    im making a car game in which you have an upper view of car
    problem is that i cant make the car rotate and move at the same time
    mean if i press up and right arrow key at the same time it just rotate or move forward
    can any one know how to do both things at the same time
    and also the car speed is very fast how can i make it moderate??
    here is the code
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.applet.*;
    import java.net.URL;
     
    public class RaceGame extends JComponent
    {
     
    static int x=560;
    static int  y=410;
     
    static int currentAngle=0;
    static double hspeed,vspeed;
    static int carspeed=0;
     
    double hangle,vangle;
     
    Image car;
    Image finish;
     
     
    Image getImage(String filename)
    {    	
    URL url = getClass().getResource(filename); 
     
    ImageIcon  icon = new ImageIcon(url);    
    return icon.getImage();
    }
     
     
    public RaceGame()
    {
    car=getImage("car1.jpeg");
    //finish=getImage("finish.jpg");
     
     
    }
     
     
     
    public void CreateBase()
    {
    JFrame frame=new JFrame("Dare2Race");
    frame.setBounds(70,30,650,500);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
     
    Container c=frame.getContentPane();
    c.add(new RaceGame());
     
    frame.addKeyListener(new adapter());
    c.setBackground(Color.BLACK);
     
     
    }
     
     
    public void rotate()
    {
    currentAngle+=1;
     
    if(currentAngle>=360)
    {
    currentAngle=0;
    }
    repaint();
    }
     
     
    public void paint(Graphics g)
    {
    super.paint(g);
     
    Graphics2D g2d=(Graphics2D)g;
     
    AffineTransform origXform=g2d.getTransform();
    AffineTransform newXform=(AffineTransform)(origXform.clone());
     
    newXform.rotate(Math.toRadians(currentAngle),x,y);
     
    g2d.setTransform(newXform);
     
    //g2d.drawImage(finish,12,10,this);
    g2d.drawImage(car,x,y,this);
     
    g2d.setTransform(origXform);
     
    g.setColor(Color.WHITE);
    g.drawLine(640,380,420,380);
    g.drawLine(640,460,320,460);
    g.drawLine(420,380,420,300);
    g.drawLine(320,460,320,380);
    g.drawLine(420,300,125,300);
    g.drawLine(320,380,230,380);
    g.drawLine(230,380,230,460);
    g.drawLine(230,460,2,460);
    g.drawLine(125,300,125,370);
    g.drawLine(125,370,105,370);
    g.drawLine(2,460,2,180);
    g.drawLine(105,370,105,300);
    g.drawLine(2,180,450,180);
    g.drawLine(105,300,105,250);
    g.drawLine(105,250,550,250);
    g.drawLine(550,250,550,20);
    g.drawLine(550,20,275,20);
    g.drawLine(450,180,450,100);
    g.drawLine(450,100,360,100);
    g.drawLine(360,100,360,160);
    g.drawLine(360,160,10,160);
    g.drawLine(10,160,10,30);
    g.drawLine(275,20,275,90);
    g.drawLine(275,90,110,90);
    g.drawLine(110,90,110,30);
    repaint();
    }
     
     
     
     
    class adapter extends KeyAdapter
    {
     
     
    public void keyPressed(KeyEvent e)
    {
     
      switch(e.getKeyCode())
      {
        case KeyEvent.VK_LEFT:
     
     
        currentAngle--;
        repaint();
        break;
     
        case KeyEvent.VK_RIGHT:
     
     
        currentAngle++;
        repaint();
        break;
     
        case KeyEvent.VK_UP:
     
        carspeed++;
     
        hangle=Math.toRadians(currentAngle);
        vangle=Math.toRadians(currentAngle);
     
        hspeed=((double)carspeed)*Math.cos(hangle);
        vspeed=((double)carspeed)*Math.sin(vangle);
     
        x = x - (int) hspeed;
        y = y - (int) vspeed;
     
        repaint();
        break;
     
        case KeyEvent.VK_DOWN:
     
        carspeed--;
     
        hangle=Math.toRadians(currentAngle);
        vangle=Math.toRadians(currentAngle);
     
        hspeed=((double)carspeed)*Math.cos(hangle);
        vspeed=((double)carspeed)*Math.sin(vangle);
     
        x = x + (int)hspeed;
        y = y + (int)vspeed;
        repaint();
        break;
      }
     
     
     
    }
     
     
    } 
     
     
     
     
    public static void main(String[]args)
    {
     
    RaceGame race=new RaceGame();
    race.CreateBase();
    //race.setDoubleBuffered(true);
    }
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem in rotating and moving image at the same time

    One suggestion so far: do the setVisible() call after everything is ready to be shown.

  3. #3
    Member Faz's Avatar
    Join Date
    Mar 2010
    Posts
    97
    Thanks
    5
    Thanked 14 Times in 14 Posts

    Default Re: Problem in rotating and moving image at the same time

    The problem is that both keys aren't registering in a text field or notepad or something hold down 1 for a while then hold down 2(don't release 1) what happens? I think this is the same problem here you could try something with threads too be honest I'm not sure how you would get that to work so do a bit of searching .

    Although one idea does spring to mind say if you had a few booleans say one for each direction and when a key stroke for that direction is detected (pressed) set the boolean as true and when it's released set it to false. And rather then have the commands carry out in the keys themselves have a method that does the work based on what booleans are true and is invoked with each keyPressed.

    As for the carSpeed being too fast instead of carSpeed++ change it to a double and say something like carSpeed += .2

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Problem in rotating and moving image at the same time

    You'll most likely need to store which buttons are pressed and deal with the combinations as they present themselves. You can keep an array which corresponds to each key, set their values upon keyPressed and unset upon keyReleased events.
    Pseudo-code
    boolean[] val = new boolean[4];//0 = left, 1 = up, 2 = right, 3 = down
    //initialize the above to false upon construction
     
    ....
    public void keyPressed(KeyEvent e){
     
    case VK_LEFT:
     
         val[0] = true;
        if ( val[1] ){//up is pressed as well
           ///VK_LEFT and VK_UP
        }else if ( val[3] ){//down is pressed as well
           //VK_LEFT and VK_DOWN
        }else{
            //only VK_LEFT
        }
    }
    public void keyReleased(KeyEvent e){
    //reset the value for the appropriate key
    case VK_LEFT:
       val[0] = false;
    ///...and so on
    }

    If you need to deal with button holds, you need to go into either a while loop or spawn a new Timer to deal with the continued event

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem in rotating and moving image at the same time

    On Windows: Look at how the keyboard responses are set in the Control panel. It will effect how fast you get events.

    Add some println() statements to all the listener methods to display when they are called and with what key. You can see how/when the system sends events to the listeners.

  6. #6
    Junior Member
    Join Date
    Jun 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem in rotating and moving image at the same time

    Thanks every one for help bt i dont know how to use timer
    and if i use while it goes into infinite loop
    any other help any one

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem in rotating and moving image at the same time

    What did you see when you added the print statements to the listener? Did the printed output occur in realtime with your key presses or were there delays, batching and some missed presses?

  8. #8
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Problem in rotating and moving image at the same time

    Quote Originally Posted by SlimShady View Post
    Thanks every one for help bt i dont know how to use timer
    and if i use while it goes into infinite loop
    any other help any one
    How to Use Swing Timers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)

    Working off the code I posted above, and using the array which specifies if a key is held, you can do something like the following (in semi-pseudo-code: you'd need to implement for each direction).
    private Timer leftHold = null;
    private class LeftTimerListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            //increment your rotation value
            //repaint your JPanel
           if ( !val[0] ){
                leftHold.stop();
           }
        }
    }
    ....
    //in the key listener
    case VK_LEFT:
         val[0] = true;
         leftHold = new Timer(60, new LeftTimerListener());//fires every 60ms
         leftHold.start();

    I will note that keyTyped events are fired when the key is held, however the method above makes the timing much easier to control which may be necessary in your case (for example, on the systems I know the second keyTyped event is fired only after a long delay)

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem in rotating and moving image at the same time

    the second keyTyped event is fired only after a long delay)
    On WinXP the delay can be set in the Control panel

  10. #10
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Problem in rotating and moving image at the same time

    Quote Originally Posted by Norm View Post
    On WinXP the delay can be set in the Control panel
    Perhaps, but in my view this defeats the purpose of write once run anywhere since other systems may not have that option (you would also have to ask the user to change it or potentially effect the performance of other applications by having the app change it directly). If the timing is hardcoded in, this isn't even an issue. Just my .02

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem in rotating and moving image at the same time

    Right.
    The OP is getting real-time responses to key presses. I don't know if that is possible because of these OS things.

Similar Threads

  1. Moving circle problem help
    By nobleisthyname in forum What's Wrong With My Code?
    Replies: 1
    Last Post: June 3rd, 2010, 11:43 AM
  2. Tikal Eclipse - Moving system time
    By leguin in forum Java IDEs
    Replies: 2
    Last Post: December 3rd, 2009, 01:34 AM
  3. MP3 Player: ID3 Tag Image Retrieval Problem for the Applet from internet
    By JavaJames in forum What's Wrong With My Code?
    Replies: 5
    Last Post: May 20th, 2009, 07:11 AM
  4. GUI problem with image in java
    By Koâk in forum AWT / Java Swing
    Replies: 6
    Last Post: May 17th, 2009, 04:17 AM
  5. Changing colors of large image in real time
    By chals in forum Java ME (Mobile Edition)
    Replies: 1
    Last Post: May 7th, 2009, 05:06 AM