Sunday, August 5, 2012

Animation basics for a vacation

Since I have a vacation this time I decided to implement some entertaining graphics. I have chosen to animate a Cassini oval.
The task is can be accomplished using polar equation:
The implementation of the animation is given by the following code:

library(animation)

xy <- function(angle, a, b) {
  ca <- cos(2 * angle)
  r2 <- a ^ 2 * ca + sqrt(a ^ 4 * ca ^ 2 - (a ^ 4 - b ^ 4))
  c(sqrt(r2) * cos(angle), sqrt(r2) * sin(angle))
}

go <- function() {
  angle <- seq(0, 2 * pi, len = 1000)
  par(mar = rep(0,4))
  b <- 1 + 0.5 * seq(0, 1, len = 31) ^ 3
  b <- c(b, 1.5, rev(b))
  for (i in b) {
    coord <- t(sapply(angle, xy, a = 1, b = i))
    plot(coord, type = "l",
      xlim = c(-2, 2), ylim = c(-1.25, 1.25))
    polygon(coord, col = "gray")
  }
}

ani.options(interval = 0.1)
saveGIF(go())

Parameter a is fixed to 1 and b changes from 1 to 1.5. In order to achieve smooth animation the sequence defining changes of b is not uniform but is more dense near 1.

And here is the result:


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.