We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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
About vectors and forces, read Shiffman's Nature of Code, he explains everything.
Thanks for the help.