The dynamic jump of a point within an area (square).

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

  1. Create an empty plot, whose x-axis and y-axis range from-5 to 5.
  2. 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.”
  3. 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)
    
}
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值