Turtle Physics

Turtle Physics preview image

1 collaborator

1 Jilai Cui (Author)

Tags

collision 

Tagged by Jilai Cui 7 months ago

physics 

Tagged by Jilai Cui 7 months ago

Visible to everyone | Changeable by everyone
Model was written in NetLogo 6.4.0 • Viewed 272 times • Downloaded 26 times • Run 0 times
Download the 'Turtle Physics' modelDownload this modelEmbed this model

Do you have questions or comments about this model? Ask them here! (You'll first need to log in.)


WHAT IS IT?

This model demonstrates a simple 2D physics simulation in NetLogo. Each turtle has properties such as mass, radius, and velocity. The model applies:

  • Gravity, pulling turtles downward,
  • Wall collisions, which bounce the turtles off the edges of the world,
  • Turtle-turtle collisions, modeling elastic collisions between circular objects.

It showcases how to update positions, velocities, and detect collisions in each time step to create a rudimentary “physics engine” in NetLogo.


HOW IT WORKS

  1. Turtle Variables
    Each turtle has:

    • vx / vy: Velocity in the x/y directions,
    • mass: Used in collision calculations,
    • radius: Used to check if two turtles overlap.
  2. Gravity
    A small negative constant is added to vy every tick, causing a downward acceleration.

  3. Movement
    Each turtle’s position (xcor, ycor) is updated by adding (vx, vy) once per tick.

  4. Boundary Collisions
    When a turtle crosses a boundary, it is pushed back into the valid area, and its velocity component (x or y) is reversed.

  5. Turtle-Turtle Collisions

    • The distance between two turtles is compared to the sum of their radii. If they overlap, they are first separated.
    • Then, their velocities are updated using simplified elastic collision formulas based on their masses.

HOW TO USE IT

  1. Buttons

    • Setup: Clears the world and creates a specified number of turtles with random positions, velocities, and masses.
    • Go: Repeatedly applies gravity, moves turtles, and checks for collisions in each tick.
    • Up: Add upward acceration to turtles
    • Mouse click: Add Force to turtles which points at the mouse location
  2. Initial Conditions

    • By default, 20 turtles are created, each with random properties (mass, velocity, radius). You can modify these values in the code or by adding a slider in the Interface tab.
  3. Running the Model

    1. Click Setup to initialize.
    2. Click Go to start the simulation.
    3. Observe how turtles move, bounce off walls, and collide with each other.

THINGS TO NOTICE

  • Mass Effect: When a light turtle collides with a heavier one, the lighter turtle’s velocity changes more dramatically.
  • Energy Exchange: In perfectly elastic collisions, kinetic energy is conserved. Turtles may exchange velocities but the total system energy (minus any gravity potential changes) remains roughly the same.
  • Gravity: Notice how gravity accelerates turtles downward. They will bounce on the “floor” boundary repeatedly.

THINGS TO TRY

  1. Vary Gravity
    Change the gravity constant in the code to see how stronger or weaker gravity affects the system.

  2. Inelastic Collisions
    Modify the collision formulas to remove some fraction of velocity (e.g., multiply velocities by 0.9) to simulate energy loss.

  3. Friction / Damping
    Multiply each velocity by a factor < 1 (e.g., 0.99) each tick to simulate drag or friction.

  4. Remove Gravity
    Comment out the apply-gravity procedure call so turtles only collide with each other and the walls.

  5. Increase Turtles
    Raise the number of turtles to see if performance changes or how collisions become more frequent.


EXTENDING THE MODEL

  • Rotational Dynamics: Give turtles angular velocity and calculate spin changes on collisions.
  • Gravitational Attraction: Replace the constant downward gravity with pairwise Newtonian attraction so turtles orbit each other.
  • Spatial Partitioning: For many turtles (hundreds or thousands), collision checks become expensive. Implement a grid or quadtree to reduce the computational load.

NETLOGO FEATURES

  • Turtles: Each turtle holds custom variables (vx, vy, mass, radius).
  • Patches: Used here primarily for setting a background color.
  • Built-In Primitives:
    • distance for measuring the distance between turtles,
    • min-pxcor / max-pxcor (and similarly pycor) for boundary detection.
  • Procedures: The model splits actions into distinct procedures (apply-gravity, move-turtles, handle-wall-collisions, handle-turtle-collisions).

RELATED MODELS

  • GasLab models in the NetLogo Models Library, which simulate elastic collisions among particles in a 2D container.
  • Particle System or other physical simulation models available in the library or on the NetLogo community website.

CREDITS AND REFERENCES

  • This code and explanation were adapted for demonstration purposes.
  • NetLogo is created by Uri Wilensky and developed at the Center for Connected Learning and Computer-Based Modeling, Northwestern University.
  • To learn more about NetLogo, visit the NetLogo website.

Comments and Questions

Please start the discussion about this model! (You'll first need to log in.)

Click to Run Model

globals[damping]

patches-own[density]

turtles-own [
  mass
  vx  ; Horizontal velocity
  vy  ; Vertical velocity
  ax  ; Horizontal acceleration
  ay  ; Vertical acceleration
  newxcor
  newycor
  radius
  restitution
]

to setup
  clear-all

  set damping 1 - damping-co  ; Velocity damping per tick (simulates air resistance)
  create-turtles ball-num [

    setxy random-xcor random-ycor
    set shape "circle"
    set radius 1.0 + random-float 1.5  ; Random radius between 0.5 and 2.0
    set size 2 * radius  ; Visual size based on collision radius

    set mass radius ^ 2
    set vx random-float 4 - 2  ; Random initial velocity
    set vy random-float 4 - 2
    set ax 0
    set ay 0
    set restitution 0.6  ; Bounciness between 0.7 and 1.0

  ]
  reset-ticks
end 

to go
  click
  apply-forces      ; Apply gravity
  update-velocities ; Integrate acceleration into velocity
  apply-damping     ; Reduce velocity due to damping
  detect-collisions ; Resolve collisions between turtles
  move-turtles      ; Update positions and handle edge bouncing
  tick
end 

to apply-forces
  ask turtles [
    set ay ay - gravity  ; Gravity affects vertical acceleration
  ]
end 

to update-velocities
  ask turtles [
    set vx vx + ax
    set vy vy + ay
    set ax 0  ; Reset acceleration
    set ay 0
  ]
end 

to apply-damping
  set damping 1 - damping-co  ; Velocity damping per tick (simulates air resistance)
  ask turtles [
    set vx vx * damping
    set vy vy * damping
  ]
end 

to detect-collisions
  ;; We only handle each pair once: for turtle i, we only compare with turtles j where j > i.
  ask turtles [
    let me self
    ask other turtles with [who > [who] of me] [

      ;; Compute the vector between me and the other turtle
      let detx (xcor - [xcor] of me)
      let dety (ycor - [ycor] of me)
      let dist distance me
      let sum-r (radius + [radius] of me)

      ;; Check overlap
      if dist  < sum-r [
        ;; If dist = 0, skip or nudge it to avoid divide-by-zero
        if dist = 0 [
          set dist 0.00000001
        ]

        ;;---------------------------------
        ;; (1) Separate the overlapping turtles
        ;;---------------------------------
        let overlap (sum-r - dist)
        let nx (detx / dist)
        let ny (dety / dist)


        let halfOverlap (overlap / 2)

        ;; Move this turtle away
        set newxcor xcor + (nx * halfOverlap)
        set newycor ycor + (ny * halfOverlap)




        ;; Move the other turtle away
        ask me [
          set newxcor xcor - (nx * halfOverlap)
          set newycor ycor - (ny * halfOverlap)
        ]

        ;;---------------------------------
        ;; (2) Compute new velocities (1D elastic collision)
        ;;---------------------------------
        let m1 mass
        let m2 [mass] of me

        let vx1 vx
        let vy1 vy
        let vx2 [vx] of me
        let vy2 [vy] of me

        set vx1 lim vx1
        set vy1 lim vy1
        set vx2 lim vx2
        set vy2 lim vy2


        ;; Compute normal velocity components
        let un1 (vx1 * nx + vy1 * ny)
        let un2 (vx2 * nx + vy2 * ny)

        ;; Compute tangential velocity components (unchanged by elastic collision)
        let ut1 (vx1 * -1 * ny + vy1 * nx)
        let ut2 (vx2 * -1 * ny + vy2 * nx)

        ;; Elastic collision formulas
        let un1Prime ((un1 * (m1 - m2) + 2 * m2 * un2) / (m1 + m2))

        let un2Prime ((un2 * (m2 - m1) + 2 * m1 * un1) / (m1 + m2))

        ;; Recombine into (vx, vy)
        set vx (un1Prime * nx + ut1 * -1 * ny)
        set vy (un1Prime * ny + ut1 *  nx)

        ask me [
          set vx (un2Prime * nx + ut2 * -1 * ny)
          set vy (un2Prime * ny + ut2 *  nx)
        ]
      ]
    ]
  ]
end 

to move-turtles
  ask turtles [

    ask patch-here[
      set pcolor [color]of myself
      set density 100
    ]

    ; Calculate new position
    set newxcor xcor + vx
    set newycor ycor + vy
    if 1 = 1[
    ; Bounce off horizontal edges
    if abs newxcor > max-pxcor - 1.5 [
      set vx (-1 * vx * restitution)
      set newxcor (sign newxcor) * (max-pxcor - 1.5)
    ]

    ; Bounce off vertical edges
    if abs newycor > max-pycor - 1.5[
      set vy (-1 * vy * restitution)
      set newycor (sign newycor) * (max-pycor - 1.5)
    ]
    ]
    setxy newxcor newycor
  ]

  ask patches[
    set density density * 0.9
    set pcolor scale-color pcolor density 0 100
  ]
end 

to-report sign [number]
  ifelse number > 0
  [ report 1
  ][
    ifelse number < 0[
      report -1
    ][
      report 0
    ]
  ]
end 

to-report lim [number]
  ifelse  number > 1E30[
    report 1E30][
    ifelse number < -1E30[
      report -1E30
    ][
     report number
    ]
  ]
end 

to up

  ask turtles[
    set ay ay + 1
  ]
end 

to click
  if mouse-down?[
    let x mouse-xcor
    let y mouse-ycor
    ask turtles[
      let d distancexy x y
      set ax ax + ( x - xcor ) / d * 0.05 / mass
      set ay ay + ( y - ycor ) / d * 0.05 / mass
    ]
  ]
end 

There is only one version of this model, created 7 months ago by Jilai Cui.

Attached files

File Type Description Last updated
Turtle Physics.png preview Preview 7 months ago, by Jilai Cui Download

This model does not have any ancestors.

This model does not have any descendants.