How does the Ship class work?

edited January 2016 in Questions about Code

The code below is taken from my programming course. It is the full program. The program is of a ship that you can move around and rotate, changing the direction of movement, based on keyboard input.

I have a few questions about the class Ship.

Why does the PVector velocity have values of (0, -1)?

Why is velocity.x assigned sin(theta) and why is velocity.y assigned -cos(theta)?

My understanding of trigonometry is a bit rough, but I thought that to find a point to rotate to (the x and y coordinates), relative to the origin of the object you are rotating, you had to multiply the trigonometry functions by the radius of the object. Here, however that does not seem to be the case.

Why do you need to translate by position.x and position.y?

How does rotate(theta) work?

I am not entirely clear on how everything else works, but these are the main things I don't understand. I hope that by understanding these key points the rest will fall into place.

Thank you for your help, it's much appreciated.

Ship ship;

void setup()
{
  size(800, 800);

  ship = new Ship();
}

void draw()
{
  background(0);

  ship.update();
  ship.render();
}

class Ship
{
  PVector position;
  PVector velocity;
  float shipWidth;
  float theta;

  Ship()
  {
    // Constructor Chaining
    this(width / 2, height / 2, 50);
  }

  Ship(float x, float y, float w)
  {
    position = new PVector(x, y);
    velocity = new PVector(0, -1);
    shipWidth = w;
    theta = 0.0f;
  }

  void update()
  {
    velocity.x = sin(theta);
    velocity.y = -cos(theta);

    velocity.mult(5);

    if(keyPressed)
    {
      if(key == CODED)
      {
        if(keyCode == UP)
        { 
          position.add(velocity);
        }

        if(keyCode == LEFT)
        {
          theta -= 0.1f;
        }

        if(keyCode == RIGHT)
        {
          theta += 0.1f;
        }
      }
    }
  }

  void render()
  {
    stroke(255);
    pushMatrix();
    translate(position.x, position.y);
    rotate(theta);
    line(-shipWidth / 2, shipWidth / 2, 0, -shipWidth / 2);
    line(shipWidth / 2, shipWidth / 2, 0, -shipWidth / 2);
    line(0, 0, shipWidth / 2, shipWidth / 2);
    line(0, 0, -shipWidth / 2, shipWidth / 2);
    popMatrix();
  }
}

Answers

  • Answer ✓
    1. velocity of (0,-1) means heading up. -1 by y axis.
    2. it is done, so when the ship will be rotated using rotate(theta), the forward direction of ship still will be forward. A little bit hard to explain actually, try the same with a line for example.
    3. Translation is used here, because it is used alongside with rotation and rotation rotates the full matrix, without translation the pivot point of rotation will be somewhere, but not in the middle of the ship.
    4. rotate just needs you to try it separately.

    About vectors and forces, read Shiffman's Nature of Code, he explains everything.

  • Thanks for the help.

Sign In or Register to comment.