Using Vectors in Processing Language
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 –
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 –
Now we have to move the ball at constant velocity. This can be done using the following code without using any vector function –
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 –
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 –
Implementation of the Ball class –
This article is contributed by Soumik Rakshit. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.