Module 13: Animating in R

 Using Yihui Xie's animation package, I opted to try to make a simple animation of a bouncing ball. While I'm more than pleased with the results, I'm still at a loss as to why the ball isn't bouncing as it should (it's meant to flatten somewhat at the bottom). Regardless, it's still fascinating to see an actual animation having been created with only R code.


Code:

library(animation)

# Function to create the animation frames
bounce_animation <- function(height = 10, gravity = 0.1, nframes = 25, x = 0.5, filename = "bounce_animation.gif") {
  # Initialize variables
  y <- height
  velocity <- 0
  squished <- FALSE
  
  # Create and save the animation
  saveGIF({
    for (i in 1:nframes) {
      # Update position and velocity
      y <- y + velocity
      velocity <- velocity - gravity
      
      # Squish effect when ball hits the ground
      if (y < 0) {
        y <- 0
        velocity <- -velocity * 0.9  # Loss of energy upon bouncing
        squished <- TRUE
      } else {
        squished <- FALSE
      }
      
      # Plot the ball with squish effect
      plot(0, 0, type = "n", xlim = c(-1, 1), ylim = c(-1, height), xlab = "", ylab = "")
      if (squished) {
        symbols(0, y, circles = 1, inches = c((0.5 * x), 0.5), aspect = 1, add = TRUE# Oval shape when squished?
      } else {
        symbols(0, y, circles = 1, inches = c(0.5, 0.5), add = TRUE# Original ball shape
      }
      
      # Pause between frames
      Sys.sleep(0.02# Adjusted delay between frames for smoother animation
    }
  }, movie.name = filename)
}

# Create and save the animation
bounce_animation(x = 0.8)

Comments

Popular posts from this blog

Module 6: Our First Graph

LIS 4317 Final Project: R Chart showing Game Price changes over time

Final Project: DescribeR v1.0.0