Before I begin I'd like to say that I submitted this post one day ago on the Processing forum but have not received a reply. The code is of a Java based framework called Processing and my problem is mainly with how the maths works in the class. Hopefully someone here will be able to help explain it to me.
---
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
Ship ship;
void setup()
{
size(800, 800);
ship = new Ship();
}
void draw()
{
background(0);
ship.update();
ship.render();
}
|
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
|
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();
}
}
|