Processing 中的向量正是它们在现实生活中的样子,一个既有大小又有方向的量。在这个例子中,我们将使用向量创建著名游戏Pong的运动机制。在Processing中,PVector类用于描述一个二维或三维的欧几里得向量。它具有以下字段 –
- x – 向量的 x 分量
- y – 向量的 y 分量
- z – 向量的 z 分量
PVector 类还有几个用于操作向量的函数,我们将在以下程序中使用add()
函数。
草图的实现——
/* SKETCH */
Ball b; // Ball object
void setup()
{
// Called at the beginning once
size(600,400);
// Initializing the new walker object with radius of the ball
b=new Ball(20);
}
void draw() // Called every frame
{
background(0); // A black background
b.display(); // Displaying the Ball object
b.move(); // Function to move the Ball
b.bounce();// Function to bounce the Ball
}
现在我们必须定义 Ball 类。我们必须定义两个 PVectors location 和 velocity 作为数据成员。我们将它们初始化如下——
PVector location, velocity;
Ball(float r)
{
// Initial position is set at the center of the screen
location = new PVector(width/2, height/2);
// Initial velocity set to 2 for in both x and y direction
velocity = new PVector(2, 2);
// Initializing radius
radius=r;
}
现在我们必须以恒定速度移动球。这可以使用以下代码完成,而无需使用任何向量函数-
void move()
{
location.x += velocity.x;
location.y += velocity.y;
}
这也可以使用 add()函数来实现,该函数是 PVector 类的成员。由于我们想将速度向量与位置向量相加,我们编写以下代码——
void move()
{
// Equivalent way of thinking:
// location += velocity
location.add(velocity);
}
最后我们需要检查球是否已经到达屏幕边缘,如果是,球需要从屏幕边缘反弹。为此,我们只需在球到达屏幕边缘时反转速度方向。我们可以使用以下代码来做到这一点——
void bounce()
{
// Code for making the ball bounce of the edges
if((location.x + radius > width) || (location.x + radius < 0))
velocity.x *= -1;
if((location.y + radius > height) || (location.y + radius < 0))
velocity.y *= -1;
}
Ball类的实现——
/* Implementation of the Ball class */
class Ball
{
PVector location, velocity;
float radius;
Ball(float r)
{
// Initial position is set at the center of the screen
location = new PVector(width/2, height/2);
// Initial velocity set to 2 for in both x and y direction
velocity = new PVector(2, 2);
// Initializing radius
radius=r;
}
void move()
{
// Equivalent way of thinking:
// location += velocity
location.add(velocity);
}
void bounce()
{
// Code for making the ball bounce of the edges
if((location.x > width) || (location.x < 0))
velocity.x *= -1;
if((location.y > height) || (location.y < 0))
velocity.y *= -1;
}
void display()
{
// Code to display the ball
noStroke();
fill(255);
ellipse(location.x, location.y, radius * 2, radius * 2);
}
}