beason4251

Star generation + simulation

Apr 16th, 2020
1,014
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 2.20 KB | None | 0 0
  1. # Generate 100 stars
  2. n <- 100
  3. # stars.m holds our galaxy
  4. stars.m <- matrix(0, n, 5)
  5.  
  6. # Add a star to the galaxy.
  7. genStar <- function(m) {
  8.   # Try 20 times to find a new spot for a star.
  9.   for (tries in 1:20) {
  10.     # Pick a radius and angle.
  11.     # Roughly, stars are a randomly-chosen integer distance from the center.
  12.     # Larger radii have a larger chance of being chosen than smaller.
  13.     radius <- 3+floor((1 - runif(1)^2) * 10)
  14.     angle <- runif(1)*2*pi
  15.    
  16.     collision = FALSE
  17.     for (i in 1:n) {
  18.       # Check all current stars in the galaxy to make sure there aren't
  19.       # any too close since it looks bad.
  20.       if (m[i, 1] == radius & (abs(m[i, 2] - angle) < ((0.25*2*pi) / radius))) {
  21.         # Too close to a star in the same ring, so try another.
  22.         collision = TRUE
  23.         break
  24.       }
  25.     }
  26.     if (!collision) {
  27.       # No collision, so we've found a new location for a star.
  28.       return(c(radius, angle))
  29.     }
  30.  }
  31.   return(c(0, 0))
  32. }
  33.  
  34. for (i in 1:n) {
  35.   # Assign radius/angle for the new star.
  36.   stars.m[i, 1:2] = genStar(stars.m)
  37.  
  38.   # Calculate x, y positions.
  39.   stars.m[i, 3] = stars.m[i, 1]*sin(stars.m[i, 2])
  40.   stars.m[i, 4] = stars.m[i, 1]*cos(stars.m[i, 2])
  41.   # Use initial angle to set the color.
  42.   stars.m[i, 5] = 1+floor(stars.m[i, 2] * 3 / pi)
  43. }
  44.  
  45. # Red, Yellow, Green, Teal, Blue, Purple
  46. cols=c("#FF0000", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#FF00FF")
  47.  
  48. # Advance the galaxy by some time.
  49. advance <- function(m, t) {
  50.   for (i in 1:n) {
  51.     # Stars closer to the center move faster.
  52.     m[i, 2] = m[i, 2] + (t / m[i, 1])
  53.    
  54.     # Update x, y positions.
  55.     m[i, 3] = m[i, 1]*sin(m[i, 2])
  56.     m[i, 4] = m[i, 1]*cos(m[i, 2])
  57.   }
  58.   return(m)
  59. }
  60.  
  61. # Plot the initial galaxy.
  62. png(filename="tick_0.png")
  63. par(bg = "black")
  64. plot(stars.m[, 3:4], col=cols[stars.m[, 5]], main="Tick 0", col.main="white")
  65. dev.off()
  66.  
  67. for (i in 1:15) {
  68.   # Advance the galaxy in day-increments and plot.
  69.   tick <- 24*i
  70.   fn <- paste0("tick_", as.character(tick), ".png")
  71.  
  72.  
  73.   png(filename=fn)
  74.   stars.m = advance(stars.m, 1)
  75.   par(bg = "black")
  76.   plot(stars.m[, 3:4], col=cols[stars.m[, 5]], main=paste("Tick", tick), col.main="white")
  77.   dev.off()
  78. }
Advertisement
Add Comment
Please, Sign In to add comment