Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (540)
Games in Android Showcase (133)
games submitted by our members
Games in WIP (603)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Basic rotation and Moving toward angle direction (car movement)  (Read 4396 times)
0 Members and 2 Guests are viewing this topic.
Offline alaslipknot
« Posted 2013-04-28 02:20:21 »

Hello,
i don't know if am able to post here or not, but i finally find the "correct" way to rotate an object and make it move toward the its rotation direction, and i decided to share it in case someone else has find himself facing the same problem i have for this whole week.

[if you found any error please correct me]

so,   
1st thing you need to know is the "head" of your object, if you draw a rectangle and its rotation angle is still 0, which mean you didn't rotate it yet, then the head is filled rectangle like this picture show
   
i don't know if am the only one who made that error, but i was thinking that the head is the upper line  Roll Eyes

anyway, here is a very simple example on how to rotate a square and make it move forward and backward (car movement )

this is the Hero class, the object that we will rotate
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
//this is the hero class

package rot;

public class Hero {

   private double x, y, a; // x,y and angle
   private int w, h; // width and height

   // constructor
   public Hero(double x, double y, double a, int w, int h) {

      this.x = x;
      this.y = y;
      this.a = a;
      this.w = w;
      this.h = h;
   }

   // returning all the necessary value of this class

   public double getX() {
      return x;
   }

   public double getY() {
      return y;
   }

   public double getA() {
      return a;
   }

   public int getW() {
      return w;
   }

   public int getH() {
      return h;
   }

   // setting the angle
   public void setA(int aa) {

      a = Math.toRadians(aa);
   }

   // move toward the angle
   // //forward
   public void moveForward() {
      x += Math.cos(a);
      y += Math.sin(a);
   }
   // //backward
   public void moveBackword() {
      x -= Math.cos(a);
      y -= Math.sin(a);
   }

}


this is the Board class, it have the game loop, the game control key and the game logic
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
package rot;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;

import javax.swing.JPanel;

public class Board extends JPanel implements Runnable {

   private Thread loop;

   private Hero hero;

   private int tmpAngle;

   private boolean moveForward, moveBackward;

   // constructor
   public Board() {
      init();
      addKeyListener(new Controll());
      setFocusable(true);
      setBackground(new Color(0, 50, 100));
      setDoubleBuffered(true);
      setFocusable(true);

   }

   // initialisation
   private void init() {
      hero = new Hero(400, 300, 0, 70, 50);
      tmpAngle = 0;
      moveForward = moveBackward = false;

      loop = new Thread(this);
      loop.start();

   }

   public void paint(Graphics g) {
      super.paint(g);

      Graphics2D g2d = (Graphics2D) g;
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
      AffineTransform old = g2d.getTransform();

      g2d.setColor(Color.white);

      // rotating the hero, rotation point is the middle of the square
      g2d.rotate(hero.getA(), hero.getX() + hero.getW() / 2, hero.getY()
            + hero.getH() / 2);
      // drawing the square
      g2d.drawRect((int) hero.getX(), (int) hero.getY(), hero.getW(),
            hero.getH());

      // to know the "head"
      g2d.fillRect((int) hero.getX() + hero.getW(), (int) hero.getY() + 10,
            10, 30);

      //in case you have other things to rotate
      g2d.setTransform(old);

   }

   public void play() {

      // this is just to keep the angle between 0 and 360
      if (tmpAngle > 360) {
         tmpAngle = 0;
      } else if (tmpAngle < 0) {
         tmpAngle = 360;

      }

      // setting the hero angle
      hero.setA(tmpAngle);

      // moving the hero
      if (moveForward) {

         hero.moveForward();
      } else if (moveBackward) {
         hero.moveBackword();
      }

   }

   // game loop
   @Override
   public void run() {

      while (true) {
         repaint();
         play();
         try {
            loop.sleep(2);
         } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }

      }

   }

   // game key controll
   private class Controll extends KeyAdapter {

      public void keyPressed(KeyEvent e) {

         if (e.getKeyCode() == e.VK_UP) {
            moveForward = true;
         }
         if (e.getKeyCode() == e.VK_DOWN) {
            moveBackward = true;
         }
         if (e.getKeyCode() == e.VK_LEFT) {
            tmpAngle -= 5;
         }
         if (e.getKeyCode() == e.VK_RIGHT) {
            tmpAngle += 5;
         }

      }

      public void keyReleased(KeyEvent e) {

         if (e.getKeyCode() == e.VK_UP) {
            moveForward = false;
         }
         if (e.getKeyCode() == e.VK_DOWN) {
            moveBackward = false;
         }
         if (e.getKeyCode() == e.VK_LEFT) {

            tmpAngle -= 0;
         }
         if (e.getKeyCode() == e.VK_RIGHT) {
            tmpAngle += 0;
         }

      }
   }

}


and finally this is the frame class, the one that have the main class
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
//this is the game window 

package rot;

import javax.swing.JFrame;

public class RotateME extends JFrame {

   private final int width = 800, height = 600;

   public RotateME() {

      add(new Board());

      setTitle("rotate me please");
      setSize(width, height);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setResizable(true);
      setVisible(true);

   }

   public static void main(String[] args) {
      new RotateME();

   }

}


i hope what i said is correct and can be helpful for new developers like me

thank you

"It's not at all important to get it right the first time. It's vitally important to get it right the last time."
Online SHC
« Reply #1 - Posted 2013-04-30 03:28:01 »

Nice article but I have some recommendations.

1  
2  
3  
4  
5  
6  
7  
-   init();
    addKeyListener(new Controll());
    setFocusable(true);
    setBackground(new Color(0, 50, 100));
    setDoubleBuffered(true);
    setFocusable(true);
+   init();

You are adding keylistener after the starting of gameloop! This can make the player think that the game is too slow if the game starts playing when it's started and input may take some time. So create keylistener first.

The second issue is with your game loop.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
while (true) {
    repaint();
    play();
    try {
       loop.sleep(2);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

You are calling
loop.sleep(2)
. You should call it like
Thread.sleep(2)
since
sleep
is a static method. Also the precision of the sleep method is not guaranteed across platforms. Please read the article Game Loops!.

Other than those, it's a nice article.

Offline alaslipknot
« Reply #2 - Posted 2013-05-04 01:36:01 »

about the calling thing, you are right, i usually do these kinda of mistake  Roll Eyes hopefully it's not that deadly, but yeah people who read this article should be aware of it.
about the loop thing, well ...
the loop am using is definitely a BAD game loop and no one should use it for a full project, but the goal here is just how to make an object move toward it's rotation (which caused a little problem for me )
otherwise, thank you for replying ^_^

"It's not at all important to get it right the first time. It's vitally important to get it right the last time."
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Mr.CodeIt (20 views)
2014-12-23 03:34:11

rwatson462 (52 views)
2014-12-15 09:26:44

Mr.CodeIt (45 views)
2014-12-14 19:50:38

BurntPizza (82 views)
2014-12-09 22:41:13

BurntPizza (110 views)
2014-12-08 04:46:31

JscottyBieshaar (78 views)
2014-12-05 12:39:02

SHC (89 views)
2014-12-03 16:27:13

CopyableCougar4 (93 views)
2014-11-29 21:32:03

toopeicgaming1999 (155 views)
2014-11-26 15:22:04

toopeicgaming1999 (150 views)
2014-11-26 15:20:36
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!