-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTut_week_9_sol.R
67 lines (56 loc) · 1.47 KB
/
Tut_week_9_sol.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
update <- function(x,v){
# TODO: Check the boundary collision, and update v.
if(x[1] > 5 || x[1] < -5){
v[1] <- - v[1]
}
if(x[2] > 5 || x[2] < -5){
v[2] <- - v[2]
}
x <- x + v #update x
return(list(x,v))
}
x <- c(0,0) #the initial position of x
v <- c(0.23456,0.12345) #the initial velocity of x
while(T){
#TODO: create a new plot and draw x's current location
plot(c(-5, 5), c(-5, 5), type = "n", xlab = "x", ylab = "y")
points(x[1],x[2])
xv <- update(x,v) # update x and v
# getting new x and v from the returned list.
# list indexing uses double brackets [[]]
x<- xv[[1]]
v<- xv[[2]]
# wait a bit to allow RStudio plot the picture.
Sys.sleep(0.1)
}
######### Version that also changes colour
update <- function(x,v){
flip <- FALSE
# TODO: Check the boundary collision, and update v.
if(x[1] > 5 || x[1] < -5){
v[1] <- - v[1]
flip <- TRUE
}
if(x[2] > 5 || x[2] < -5){
v[2] <- - v[2]
flip <- TRUE
}
x <- x + v #update x
return(list(x,v,flip))
}
flip <- FALSE
cl <- FALSE
while(T){
if(flip){ cl <- !cl }
#TODO: create a new plot and draw x's current location
plot(c(-5, 5), c(-5, 5), type = "n", xlab = "x", ylab = "y")
points(x[1], x[2], col = cl + 1)
xv <- update(x,v) # update x and v
# getting new x and v from the returned list.
# list indexing uses double brackets [[]]
x <- xv[[1]]
v <- xv[[2]]
flip <- xv[[3]]
# wait a bit to allow RStudio plot the picture.
Sys.sleep(0.1)
}