VPython (Visual Python) is a 3D graphics library that allows us to create and visualize three-dimensional objects on the screen. It is primarily used to visualize the impact of physics equations on the objects' motion.
Note: Read more about VPython.
The labels are graphical objects that allow us to display text within a 3D scene. They are used to provide annotations for various objects in the scene.
The syntax for adding a label to an object is as follows:
label(pos, text, xoffset, yoffset)
where the parameters are:
pos: It is a vector object, which sets the position of the label in the scene. We must provide the same pos to the label as its corresponding object.
text: We pass the label's display string to the text parameter.
xoffset and yoffset: These parameters take integer values that move the label in the
To execute the code example provided, follow the steps mentioned in the slides below:
The following sample code creates a box, cone, and moving sphere in the scene and assigns relevant labels to them. The moving ball's label moves with the sphere.
from vpython import *
import numpy as np
# Create a scene
canvas(width=600, height=600)
# Create the objects
sq = box(size=vector(0.5, 0.01, 0.5), pos=vector(-2, 0.5, 0))
tr = cone(pos=vector(2, 0.2, 0.6), size=vector(0.5, 0.5, 0.5), color=color.yellow)
ball = sphere(radius=0.2, color=color.red, pos=vector(0, -1, 0))
# Create a label
info_label_1 = label(pos=vector(-2, 0.5, 0), text="This is a box object.", xoffset=10, yoffset=20)
info_label_2 = label(pos=vector(2, 0.2, 0.6), text="This is a cone object.", xoffset=10, yoffset=20)
annotation = label(pos=vector(0, ball.pos.y, 0), text="Moving Ball", xoffset=20, yoffset=20)
i = 2
direction = 1 # 1 for increasing, -1 for decreasing
while True:
rate(100) # Reduce the animation rate
ball.pos.y = 1 - i
ball.pos = vector(0, ball.pos.y, 0)
annotation.pos = vector(0, ball.pos.y, 0) # Update the annotation position
if direction == 1:
i += 0.005
if i >= 4:
direction = -1
else:
i -= 0.005
if i <= 2:
direction = 1Lines 1–2: Importing the necessary library.
Line 5: Creating a window for the scene.
Lines 8–10: Three objects (box, cone and sphere) are created. Out of these three objects, only the sphere moves back and forth.
Lines 13–15: Assigning the labels to the relevant objects.
Note: The labels have same
posvectors as their corresponding objects.
Line 17–18: i is an iterator in the loop below. The direction is positive if the ball moves upwards and negative if it goes downwards.
Line 21: The rate() specifies the frames per second of the animation.
Lines 22–24: Repeatedly update the sphere's position and label.
Lines 26–33: Changing the sphere's direction.
Free Resources