Using Vectors in Processing Language
Last Updated :
29 Sep, 2022
Vectors in Processing are exactly what they are in real life, a quantity that has both magnitude and direction. In this example we will create the movement mechanics of the famous game Pong using vectors. In Processing, the PVector class is used to describe a two or three dimensional Euclidean vector. It has the following fields –
- x – The x component of the vector
- y – The y component of the vector
- z – The z component of the vector
The PVector class also has several functions for manipulation of vectors, of which we will be using the add()
function for the following program.
Implementation of sketch –
Ball b;
void setup()
{
size( 600 , 400 );
b= new Ball( 20 );
}
void draw()
{
background( 0 );
b.display();
b.move();
b.bounce();
}
|
Now we have to define the Ball class. We have to define two PVectors location and velocity as data members. We initialize them as follows –
PVector location, velocity;
Ball( float r)
{
location = new PVector(width/ 2 , height/ 2 );
velocity = new PVector( 2 , 2 );
radius=r;
}
|
Now we have to move the ball at constant velocity. This can be done using the following code without using any vector function –
void move()
{
location.x += velocity.x;
location.y += velocity.y;
}
|
This can also be achieved using the add() function which is a member of the PVector class. Since we want to add the velocity vector to location vector, we write the following code –
void move()
{
location.add(velocity);
}
|
Finally we need to check, whether the ball has reached the edge of the screen or not and if so, the ball needs to bounce off the edge of the screen. To do so, we just reverse the direction of velocity once the ball reaches edge of the screen. We can do so using the following code –
void bounce()
{
if ((location.x + radius > width) || (location.x + radius < 0 ))
velocity.x *= - 1 ;
if ((location.y + radius > height) || (location.y + radius < 0 ))
velocity.y *= - 1 ;
}
|
Implementation of the Ball class –
class Ball
{
PVector location, velocity;
float radius;
Ball( float r)
{
location = new PVector(width/ 2 , height/ 2 );
velocity = new PVector( 2 , 2 );
radius=r;
}
void move()
{
location.add(velocity);
}
void bounce()
{
if ((location.x > width) || (location.x < 0 ))
velocity.x *= - 1 ;
if ((location.y > height) || (location.y < 0 ))
velocity.y *= - 1 ;
}
void display()
{
noStroke();
fill( 255 );
ellipse(location.x, location.y, radius * 2 , radius * 2 );
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...