|
| 1 | +# The Nature of Code |
| 2 | +# Daniel Shiffman |
| 3 | +# http://natureofcode.com |
| 4 | + |
| 5 | +# A circular particle |
| 6 | +class Particle |
| 7 | + extend Forwardable |
| 8 | + def_delegators(:@app, :fill, :stroke, :stroke_weight, :box2d, :height, :line, |
| 9 | + :push_matrix, :pop_matrix, :ellipse, :rotate, :translate) |
| 10 | + # We need to keep track of a Body and a radius |
| 11 | + attr_reader :body, :r |
| 12 | + |
| 13 | + def initialize(x, y) |
| 14 | + @r = 8 |
| 15 | + @app = $app |
| 16 | + # Define a body |
| 17 | + bd = BodyDef.new |
| 18 | + # Set its position |
| 19 | + bd.position = box2d.processing_to_world(x, y) |
| 20 | + bd.type = BodyType::DYNAMIC |
| 21 | + @body = box2d.world.createBody(bd) |
| 22 | + |
| 23 | + # Make the body's shape a circle |
| 24 | + cs = CircleShape.new |
| 25 | + cs.m_radius = box2d.scale_to_world(r) |
| 26 | + |
| 27 | + fd = FixtureDef.new |
| 28 | + fd.shape = cs |
| 29 | + # Parameters that affect physics |
| 30 | + fd.density = 1 |
| 31 | + fd.friction = 0.01 |
| 32 | + fd.restitution = 0.3 |
| 33 | + |
| 34 | + # Attach fixture to body |
| 35 | + body.createFixture(fd) |
| 36 | + body.setLinearVelocity(Vec2.new(rand(-5..5), rand(2..5))) |
| 37 | + end |
| 38 | + |
| 39 | + # This function removes the particle from the box2d world |
| 40 | + def kill_body |
| 41 | + box2d.destroy_body(body) |
| 42 | + end |
| 43 | + |
| 44 | + # Is the particle ready for deletion? |
| 45 | + def done |
| 46 | + # Let's find the screen position of the particle |
| 47 | + pos = box2d.body_coord(body) |
| 48 | + # Is it off the bottom of the screen? |
| 49 | + if pos.y > height + r * 2 |
| 50 | + kill_body |
| 51 | + return true |
| 52 | + end |
| 53 | + false |
| 54 | + end |
| 55 | + |
| 56 | + def display |
| 57 | + # We look at each body and get its screen position |
| 58 | + pos = box2d.body_coord(body) |
| 59 | + # Get its angle of rotation |
| 60 | + a = body.get_angle |
| 61 | + push_matrix |
| 62 | + translate(pos.x, pos.y) |
| 63 | + rotate(a) |
| 64 | + fill(127) |
| 65 | + stroke(0) |
| 66 | + stroke_weight(2) |
| 67 | + ellipse(0, 0, r * 2, r * 2) |
| 68 | + # Let's add a line so we can see the rotation |
| 69 | + line(0, 0, r, 0) |
| 70 | + pop_matrix |
| 71 | + end |
| 72 | +end |
0 commit comments