Background
It is inspired by a scene in the TV show “The Office”:
https://www.youtube.com/watch?v=QOtuX0jL85Y
Task
We are going to write an animated visualization that mimics the DVD logo bouncing around the edge of the TV.
Idea
- Create an empty plot, whose x-axis and y-axis range from-5 to 5.
- Initialize two vectors:
x = (0,0) y = (0.23456,0.12345)
Draw the vector as a red dot in the plot.
Add plot title: “point simulation, press ESC to stop.” - Write a function that updates the point x’s location based on the velocity vector v. If the position of x is slightly out of the box, the point will be bounced back.
Code
Note: The list combines two vectors and allows you to return multiple values from a function
update function(x,v){
# Check the boundary collision, and update v.
if(x[1] > 5 | x[1] < -5){
v[1] <- (-v[1])
v[2] <- v[2]
}
if(x[2] > 5 | x[2] < -5){
v[1] <- v[1]
v[2] <- (-v[2])
}
x <- x + v
return(list(x,v))
}
x <- c(0,0) #the initial position of x
v <- c(0.23456,0.12345) #the initial velocity of x
i = 1
while (T) {
# choose the different colors
# use colorRampPalette to set the range of color
fun_color_range <- colorRampPalette(c("#1b98e0","red"))
mycolors <- fun_color_range(100)
#create a new plot and draw x's current location
plot(c(-5,5),c(-5,5), type ="n", xlab ="x", ylab ="y",main = bquote("point simulation, press ESC to stop."))
points(x[1],x[2],col = mycolors[i],type = "p",pch = 19,cex=1.2)
xv <- update(x,v)
# getting new x and v from the returned list.
# list indexing uses double brackets [[]]
x <- xv[[1]]
v <- xv[[2]]
i = i + 1
# wait a bit to allow RStudio plot the picture.
Sys.sleep(0.1)
}