Mastering 3D Animation: Creating a Bouncing Ball with Damping Effect in VPython

Mastering 3D Animation: Creating a Bouncing Ball with Damping Effect in VPython


Introduction:

In the world of computer graphics and animation, creating realistic simulations of physical phenomena is a key skill. One such phenomenon is the simulation of a bouncing ball with a damping effect, which can be achieved using VPython, a Python library for 3D modeling and animation. In this tutorial, we'll dive into the world of 3D animation and learn how to create a captivating bouncing ball animation with a damping effect using VPython.



Code : 

from vpython import *


# Constants

radius = 0.5

height = 0.5

damping = 0.9

g = vector(0, -9.81, 0)  # Acceleration due to gravity


# Scene setup

scene = canvas(title='Bouncing Ball', width=800, height=600, center=vector(0, 0, 0), background=color.white)

floor = box(pos=vector(0, -height, 0), size=vector(10, 0.1, 10), color=color.blue)

#, make_trail=True

ball = sphere(pos=vector(0, 5, 0), radius=radius, color=color.red)


# Initial conditions

ball.velocity = vector(0, 0, 0)


# Simulation loop

dt = 0.01

while True:

    rate(100)

    

    # Update velocity

    ball.velocity += g * dt

    

    # Update position

    ball.pos += ball.velocity * dt

    

    # Check for collision with floor

    if ball.pos.y - radius < floor.pos.y + floor.size.y / 2:

        ball.pos.y = floor.pos.y + floor.size.y / 2 + radius  # Prevent ball from sinking into the floor

        ball.velocity.y *= -damping  # Reverse y-velocity and apply damping

    

    # Check for ball leaving the scene

    if ball.pos.y - radius < floor.pos.y + floor.size.y / 2 and ball.velocity.y < 0:

        ball.velocity.y *= -damping  # Reverse y-velocity and apply damping



Setting the Stage:

Before we start coding, let's set the stage for our animation. We'll create a 3D scene with a floor and a ball that will bounce on the floor. The floor will act as a solid surface, and the ball will exhibit a damping effect, losing some of its energy with each bounce.


Breaking Down the Code:


We start by importing the necessary modules from VPython.

Next, we define the constants such as the radius and height of the ball, the damping factor, and the acceleration due to gravity.

We then set up the 3D scene with a floor and a ball, and define the initial conditions for the ball's position and velocity.

In the simulation loop, we update the ball's position and velocity based on the laws of physics, and apply the damping effect when the ball hits the floor.

Finally, we ensure that the animation continues running indefinitely by using the while True loop. 

Post a Comment

0 Comments