Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Generate 100 stars
- n <- 100
- # stars.m holds our galaxy
- stars.m <- matrix(0, n, 5)
- # Add a star to the galaxy.
- genStar <- function(m) {
- # Try 20 times to find a new spot for a star.
- for (tries in 1:20) {
- # Pick a radius and angle.
- # Roughly, stars are a randomly-chosen integer distance from the center.
- # Larger radii have a larger chance of being chosen than smaller.
- radius <- 3+floor((1 - runif(1)^2) * 10)
- angle <- runif(1)*2*pi
- collision = FALSE
- for (i in 1:n) {
- # Check all current stars in the galaxy to make sure there aren't
- # any too close since it looks bad.
- if (m[i, 1] == radius & (abs(m[i, 2] - angle) < ((0.25*2*pi) / radius))) {
- # Too close to a star in the same ring, so try another.
- collision = TRUE
- break
- }
- }
- if (!collision) {
- # No collision, so we've found a new location for a star.
- return(c(radius, angle))
- }
- }
- return(c(0, 0))
- }
- for (i in 1:n) {
- # Assign radius/angle for the new star.
- stars.m[i, 1:2] = genStar(stars.m)
- # Calculate x, y positions.
- stars.m[i, 3] = stars.m[i, 1]*sin(stars.m[i, 2])
- stars.m[i, 4] = stars.m[i, 1]*cos(stars.m[i, 2])
- # Use initial angle to set the color.
- stars.m[i, 5] = 1+floor(stars.m[i, 2] * 3 / pi)
- }
- # Red, Yellow, Green, Teal, Blue, Purple
- cols=c("#FF0000", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#FF00FF")
- # Advance the galaxy by some time.
- advance <- function(m, t) {
- for (i in 1:n) {
- # Stars closer to the center move faster.
- m[i, 2] = m[i, 2] + (t / m[i, 1])
- # Update x, y positions.
- m[i, 3] = m[i, 1]*sin(m[i, 2])
- m[i, 4] = m[i, 1]*cos(m[i, 2])
- }
- return(m)
- }
- # Plot the initial galaxy.
- png(filename="tick_0.png")
- par(bg = "black")
- plot(stars.m[, 3:4], col=cols[stars.m[, 5]], main="Tick 0", col.main="white")
- dev.off()
- for (i in 1:15) {
- # Advance the galaxy in day-increments and plot.
- tick <- 24*i
- fn <- paste0("tick_", as.character(tick), ".png")
- png(filename=fn)
- stars.m = advance(stars.m, 1)
- par(bg = "black")
- plot(stars.m[, 3:4], col=cols[stars.m[, 5]], main=paste("Tick", tick), col.main="white")
- dev.off()
- }
Advertisement
Add Comment
Please, Sign In to add comment