Skip to content

Instantly share code, notes, and snippets.

@jirilukavsky
Last active April 7, 2021 17:55
Show Gist options
  • Save jirilukavsky/8e84a4f0e4e5e19257ea9616ed4e95e4 to your computer and use it in GitHub Desktop.
Save jirilukavsky/8e84a4f0e4e5e19257ea9616ed4e95e4 to your computer and use it in GitHub Desktop.
Accelerating circular movements in motrack. Example of custom step_function and variable speed.
library(tidyverse)
library(motrack)
f1 <- function(time, moment) {
# base speed = 3, acceleration (increasing by) 1 deg/s^2
3 + time
}
position <- tibble(object = 1:4, x = c(-7, 5, 7, -5), y = c(5, 7, -5, -7))
position <- position %>% mutate(rx = c(-5, 5, 5, -5), ry = c(5, 5, -5, -5))
position <- position %>% mutate(rot = c("cw", "cw", "ccw", "ccw"))
position <- position %>% mutate(speed = c(f1))
plot_position(position) + geom_point(aes(x = rx, y = ry))
step_planet <- function(moment, time_next, settings) {
time_now <- moment$time[1]
timestep <- time_next - time_now
# calculate angles
# 0 = 3 o'clock, pi/2 = 12 o'clock, pi = 9 o'clock, 3*pi/2 = 6 o'clock
# initial angle relative to orbit center
a <- atan2(moment$y - moment$ry, moment$x - moment$rx)
# radius
r <- sqrt((moment$y - moment$ry)^2 + (moment$x - moment$rx)^2)
# current speed
s <- cur_speed(moment, time_now)
# cat(s) # uncomment to see the actual speeds
# angle change corresponding to arc length, speed and radius
d_a <- s * timestep / r
# new angle realtive to orbit center
new_a <- if_else(moment$rot == "cw", a - d_a, a + d_a)
# we don't use `extrapolate_moment` because we want to avoid linear segments
moment_next <- moment %>%
dplyr::mutate(
x = .data$rx + cos(new_a) * r,
y = .data$ry + sin(new_a) * r,
time = time_next
)
moment_next
}
sett_move <-
new_settings(
xlim = c(-9, 9), ylim = c(-9, 9),
bounce_off_square = F,
bounce_off_circle = T, circle_bounce_jitter = pi / 6
)
timescale <- seq(0, 8, by = 0.1)
trajectory_p <-
make_random_trajectory(
position, timescale, sett_move,
step_planet
)
plot_trajectory(trajectory_p)
animation::ani.options(ffmpeg = "/opt/homebrew/bin/ffmpeg") # update to your path
render_trajectory_video("trajectory_p.mp4", trajectory_p,
new_settings(show_labels = T),
targets = 1:4
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment