GPWiki.org
GPWiki.org
It is currently Sat May 25, 2013 10:28 pm

All times are UTC




Post new topic Reply to topic  [ 16 posts ] 
Author Message
PostPosted: Fri Mar 16, 2012 5:48 am 
Bit Baby

Joined: Sat Nov 26, 2011 3:21 am
Posts: 9
Hello. Please exscuze the wall of code that is about to incinerate your eyeballs. But im having trouble moving this little box. Basically if you hold down left it rotates the box anti clockwise and right clockwise. And then what ever angle it facing i want to to move forward in that direction with a given distance. How i designed it is that the box rotates around a center point and then im trying to move the center point along the angle, but for some reason its not working, if you compile and run youll see what i mean. I indicated in commented line where the problem is.

Code:
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.applet.*;

public class App extends Applet implements Runnable, KeyListener
{
    Thread runner;
    Image Buffer;
    Graphics gBuffer;
    //cx, cy = center of rotation
    int angle, cx, cy;
    //variables for rotation
    double radians = 0.0;
    public double cos = 1.0;
    public double sin = 0.0;
    boolean left, right;

    public void init()
    {
       this.setSize(600,400);
        //create graphics buffer, the size of the applet
        Buffer=createImage(size().width,size().height);
        gBuffer=Buffer.getGraphics();
        cx= 200;
        cy= 200;
        this.addKeyListener(this);
    }

    public void start()
    {
        if (runner == null)
        {
            runner = new Thread (this);
            runner.start();
        }
    }

    public void stop()
    {
        if (runner != null)
        {
            runner.stop();
            runner = null;
        }
    }

    public void run()
    {
        while(true)
        {
            try {runner.sleep(20);}
            catch (Exception e) { }
           
            checkRotation();
            moveForward();
            repaint();
        }
    }
    //rotates x coordinate from the square array
    int rotate_x(int x, int y)
    {
        return ((int) (cx + x * cos - y * sin) );
    }
    //rotates y coordinate from the square array
    int rotate_y(int x, int y)
    {
        return ((int) (cy + y * cos + x * sin) );
    }

    //setting angle to radians
    void SetAngle(double a)
    {
        radians = Math.toRadians(angle);

        cos = Math.cos(radians);
        sin = Math.sin(radians);
    }
   
   //THIS IS THE PROBEMS !!! ITS NOOOOT WORKING!!
   public void moveForward()
   {
      cx += 1 * cos;
      cy += 1 * sin;
   }

    public void RotatePolygon(int x[], int y[], int n)
    {
        int new_x[] = new int [n];
        int new_y[] = new int [n];

        for(int i=0; i<n; i++)
        {
            new_x[i]=rotate_x(x[i], y[i]);
            new_y[i]=rotate_y(x[i], y[i]);
        }

        gBuffer.fillPolygon(new_x, new_y, n);
    }

    void drawStuff()
    {
       
        //paint background black
        gBuffer.setColor(Color.black);
        gBuffer.fillRect(0,0,size().width,size().height);
       
        int radius;
        int x[];
        int y[];

        //drawing the square
        radius=0;
        x= new int[4];
        y= new int[4];

        x[0]=-20;
        x[1]=20;
        x[2]=20;
        x[3]=-20;

        y[0]=20;
        y[1]=20;
        y[2]=-40;
        y[3]=-40;

        gBuffer.setColor(Color.red);
        RotatePolygon(x, y, 4);

        //display the angle in degrees
        gBuffer.setColor(Color.yellow);
        gBuffer.setFont(new Font("Helvetica",Font.PLAIN,13));
        gBuffer.drawString("Angle="+angle+"°",10,20);

        gBuffer.drawString("Left " + left + "    Right " + right, 200, 20);
        gBuffer.drawString("cx " + cx + "    cy " + cy, 200, 35);
       
        //the center mark
        gBuffer.setColor(Color.white);
        gBuffer.drawOval(cx-2,cy-2, 4, 4);
       
        SetAngle(angle);
    }
   
    //checks if left or right arrow key is pressed
    public void checkRotation() {
       if(left) {
            if(angle>0)
                angle -= 6;
            else
                angle=360;
       }
       
       if(right) {
            if(angle<360)
                angle += 6;
            else
                angle=0;
        }
    }

    public void update(Graphics g)
    {
        paint(g);
    }

    public void paint(Graphics g)
    {
        drawStuff();
        g.drawImage (Buffer,0,0, this);
    }

   @Override
   public void keyPressed(KeyEvent e) {
       int keyCode = e.getKeyCode();
       switch( keyCode ) {
           case KeyEvent.VK_UP:
               // handle up
               break;
           case KeyEvent.VK_DOWN:
               // handle down
               break;
           case KeyEvent.VK_LEFT:
               left = true;
               break;
           case KeyEvent.VK_RIGHT :
               right = true;
               break;
      }
   }

   @Override
   public void keyReleased(KeyEvent e) {
       int keyCode = e.getKeyCode();
          switch( keyCode ) {
              case KeyEvent.VK_UP:
                  // handle up
                  break;
              case KeyEvent.VK_DOWN:
                  // handle down
                  break;
              case KeyEvent.VK_LEFT:
                  left = false;
                  break;
              case KeyEvent.VK_RIGHT :
                  right = false;
                  break;
         }
   }

   @Override
   public void keyTyped(KeyEvent arg0) {
      // TODO Auto-generated method stub
      
   }
}


Top
 Profile  
 
PostPosted: Fri Mar 16, 2012 11:35 am 
Funky Monkey

Joined: Thu Sep 09, 2004 1:17 pm
Posts: 1553
Location: burrowed
I don't have much time, so i cannot be elaborate on the topic right now but you should look up how vectors work.
I think there's tutorials for that in the wiki.

_________________
Long pork is people!

wzl's burrow


Top
 Profile  
 
PostPosted: Fri Mar 16, 2012 12:01 pm 
I believe I have the math you need, when I get home il dig it up.

-Meneliki


Top
  
 
PostPosted: Fri Mar 16, 2012 4:40 pm 
Source Code Swashbuckler
User avatar

Joined: Wed Nov 09, 2011 3:58 am
Posts: 199
Location: Brazil
Code:
    FPosX, FPosY : Extended; // or Float;
    FRotation : Extended; // or Float;
    FRotationSpeed : Extended; // or Float;
    FSpeed : Extended; // or Float;

Initialize variables:
Code:
    Self.FPosX := Self.Width div 2;
    Self.FPosY := Self.Height div 2;
    Self.FRotation := 0;
    Self.FRotationSpeed := 1; // This is the angle increment
    FSpeed := 1.3;

Get the pressed keys:
Code:
  if Key = LEFTARROW then
  begin
    FRotation := FRotation + FRotationSpeed;
  end;
  if Key = RIGHTARROW then
  begin
    FRotation := FRotation - FRotationSpeed;
  end;

  if FRotation > 360 then
  begin
    FRotation := 0;
  end;
  if FRotation < 0 then
  begin
    FRotation := 360;
  end;
 
  if Key = UPARROW then
  begin
    FPosX := FPosX + (FSpeed * cos(FRotation * PI / 180));
    FPosY := FPosY + (FSpeed * sin(FRotation * PI / 180));
  end;
  if Key = DOWNARROW then
  begin
    FPosX := FPosX - (FSpeed * cos(FRotation * PI / 180));
    FPosY := FPosY - (FSpeed * sin(FRotation * PI / 180));
  end;

  // Repaint the window;

Draw window:
Code:
SetPixel(Trunc(FPosX), Trunc(FPosY));

_________________
"Life finds a way." - Ian Malcolm
My WebBlog: PixelDeveloper
English is not my native language, so excuse me for any writing mistakes.


Top
 Profile  
 
PostPosted: Fri Mar 16, 2012 5:03 pm 
Bit Baby

Joined: Sat Nov 26, 2011 3:21 am
Posts: 9
Ok cool thank you for the replies. but alas, i have life to attend to, (late shift) so will have a proper look over later on. Also felipe. What language is that?. Doesnt look like java. Thanks


Top
 Profile  
 
PostPosted: Fri Mar 16, 2012 5:04 pm 
Quote:
FPosX := FPosX + (FSpeed * cos(FRotation * PI / 180));
FPosY := FPosY + (FSpeed * sin(FRotation * PI / 180));
end;
if Key = DOWNARROW then
begin
FPosX := FPosX - (FSpeed * cos(FRotation * PI / 180));
FPosY := FPosY - (FSpeed * sin(FRotation * PI / 180));


That looks about right. Thanks Felipe!

-Meneliki


Top
  
 
PostPosted: Fri Mar 16, 2012 7:11 pm 
Source Code Swashbuckler
User avatar

Joined: Wed Nov 09, 2011 3:58 am
Posts: 199
Location: Brazil
That is Pascal, but it is easy to translate to Java. You just need a "Math" library.

_________________
"Life finds a way." - Ian Malcolm
My WebBlog: PixelDeveloper
English is not my native language, so excuse me for any writing mistakes.


Top
 Profile  
 
PostPosted: Fri Mar 16, 2012 7:53 pm 
Source Code Swashbuckler
User avatar

Joined: Wed Nov 09, 2011 3:58 am
Posts: 199
Location: Brazil
Does anyone know how to do what I just did(Move along the axis with given angle and speed), but with Z axis?

I did not tried, but I think I could use Cos or Sin, no matters. One of them is the wrong, and, I think, that the only wrong effect would be the object moving in the opposite direction(up instead of down, down instead of up). Am I right?

I am implementing my engine, and I am in this part. :yeah

_________________
"Life finds a way." - Ian Malcolm
My WebBlog: PixelDeveloper
English is not my native language, so excuse me for any writing mistakes.


Top
 Profile  
 
PostPosted: Fri Mar 16, 2012 8:28 pm 
Funky Monkey

Joined: Thu Sep 09, 2004 1:17 pm
Posts: 1553
Location: burrowed
http://content.gpwiki.org/index.php/Vector
http://code.google.com/p/slimmath/sourc ... Vector2.cs
http://code.google.com/p/slimmath/sourc ... Vector3.cs

These will explain it better than i could presumably.
If you have any further questions, go ahead, but vectormath is generally pretty straight forward.

_________________
Long pork is people!

wzl's burrow


Top
 Profile  
 
PostPosted: Fri Mar 16, 2012 9:53 pm 
Grand Optimizer
User avatar

Joined: Mon Jan 17, 2005 6:01 pm
Posts: 352
Location: Canada
Ultimately it doesn't matter what language it's written in.. the idea is to translate that logic into whatever language you're using.

_________________
"None are more hopelessly enslaved than those who falsely believe they are free."
"It is no measure of health to be well adjusted to a profoundly sick society."
"Hope is the first step on the road to dissapointment." -Jonah Orion
http://tankzgame.blogspot.com


Top
 Profile  
 
PostPosted: Sat Mar 17, 2012 1:15 am 
Bit Baby

Joined: Sat Nov 26, 2011 3:21 am
Posts: 9
Meh. Im pretty sure all my math is correct. It just doesnt seem to work. I think it might be the way ive structured the program. Gona have a little play about but i will be back!


Top
 Profile  
 
PostPosted: Sat Mar 17, 2012 9:03 am 
Bytewise

Joined: Sun Oct 16, 2011 3:09 pm
Posts: 277
Location: Here (where else?)
I am somewhat intrigued by your
Code:
void SetAngle(double a)
The 'a' variable does not seem used at all.

Code:
//THIS IS THE PROBEMS !!! ITS NOOOOT WORKING!!
public void moveForward()
{
   cx += 1 * cos;
   cy += 1 * sin;
}
I would indeed expect this not to work. 'cos' and 'sin' are fractions between -1 and 1, so 1*cos and 1*sin are between -1 and 1, which get rounded down to 0, and adding 0 does not have much effect :p

Perhaps use 'double' or 'float' or so for you coordinates?

_________________
My project: Messing about in FreeRCT, dev blog, and IRC #freerct at oftc.net


Top
 Profile  
 
PostPosted: Sat Mar 17, 2012 11:39 am 
Harmlessness does no harm
User avatar

Joined: Tue Sep 14, 2004 8:37 pm
Posts: 3810
Location: Ferriday, LA, US
Good spot, Albert!

I had forgotten the way Java does things like that. If you use an integer value on the left-hand side of an equation, the result will be an integer as well. To fix that, you should cast integer values:

Code:
(double)1 * cos;


Also, instead of using '(double)1', it may also work with a simple '1.0'. This error, along with several others -- including the "SetAngle(double a)" function and its non-use of the argument 'a' -- seems to be the problem.

GinTox, you may find it a more helpful approach to describe the nature of any issues you have from now on. "It doesn't work" is usually insufficient -- no one knows exactly what that means when someone else says it. This makes it more difficult to pinpoint the problem, being that many will be unable to compile and run your game (not everyone has a Java compiler, or the will to compile/run other people's random code) to try and figure out what isn't working.

_________________
What most people don't understand about "enlightenment" is that it is not an end-goal; but where you find yourself just before taking a new "first step."


Top
 Profile  
 
PostPosted: Sat Mar 17, 2012 2:52 pm 
Bytewise

Joined: Sun Oct 16, 2011 3:09 pm
Posts: 277
Location: Here (where else?)
Euhm, casting the 1 to 'double' has no effect. You still have a fraction below 1 and above -1 that gets rounded down.

Either make cx and cy use floating point too, or multiply with a bigger number than 1 (but that will only reduce the effect of rounding rather than eliminate it).

_________________
My project: Messing about in FreeRCT, dev blog, and IRC #freerct at oftc.net


Top
 Profile  
 
PostPosted: Sat Mar 17, 2012 3:01 pm 
Harmlessness does no harm
User avatar

Joined: Tue Sep 14, 2004 8:37 pm
Posts: 3810
Location: Ferriday, LA, US
Alberth wrote:
Euhm, casting the 1 to 'double' has no effect. You still have a fraction below 1 and above -1 that gets rounded down.


Ah -- I didn't notice that cx and cy were declared 'int'...

Even if cx and cy are declared double/float, you would still need to explicitly type the 1 as a real number in Java, or the return value will be an integer. I've been bitten by this issue before, I just forgot about it a while after I had abandoned Java.

_________________
What most people don't understand about "enlightenment" is that it is not an end-goal; but where you find yourself just before taking a new "first step."


Top
 Profile  
 
PostPosted: Sat Mar 17, 2012 9:15 pm 
Bit Baby

Joined: Sat Nov 26, 2011 3:21 am
Posts: 9
Omg thank you so much, that worked :)


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 16 posts ] 

All times are UTC


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
Jump to:  
Powered by phpBB® Forum Software © phpBB Group