|
| 1 | +# The Nature of Code |
| 2 | +# <http://www.shiffman.net/teaching/nature> |
| 3 | +# Spring 2012 |
| 4 | +# Box2DProcessing example |
| 5 | + |
| 6 | +# A blob skeleton |
| 7 | +# Could be used to create blobbly characters a la Nokia Friends |
| 8 | +# http://postspectacular.com/work/nokia/friends/start |
| 9 | + |
| 10 | +class Bubble |
| 11 | + include Processing::Proxy |
| 12 | + # A list to keep track of all the points in our blob |
| 13 | + attr_reader :outline, :radius, :total_points, :hue |
| 14 | + # We should modify this constructor to receive arguments |
| 15 | + # So that we can make many different types of blobs |
| 16 | + |
| 17 | + def initialize(pos:, hue:) |
| 18 | + # Create the empty outline |
| 19 | + @outline = [] |
| 20 | + @hue = hue |
| 21 | + # Let's make a volume of joints! |
| 22 | + cvjd = ConstantVolumeJointDef.new |
| 23 | + # Where and how big is the blob |
| 24 | + center = Vec2.new(pos.x, pos.y) |
| 25 | + @total_points = 150 |
| 26 | + @radius = 25 |
| 27 | + # Initialize all the points |
| 28 | + total_points.times do |i| |
| 29 | + # Look polar to cartesian coordinate transformation! |
| 30 | + theta = map1d(i, 0..total_points, 0..TWO_PI) |
| 31 | + x = center.x + radius * sin(theta) |
| 32 | + y = center.y + radius * cos(theta) |
| 33 | + # Make each individual body |
| 34 | + bd = BodyDef.new |
| 35 | + bd.type = BodyType::DYNAMIC |
| 36 | + bd.fixedRotation = true # no rotation! |
| 37 | + bd.position.set(box2d.processing_to_world(Vec2.new(x, y))) |
| 38 | + body = box2d.createBody(bd) |
| 39 | + # The body is a circle |
| 40 | + cs = CircleShape.new |
| 41 | + cs.m_radius = box2d.scale_to_world(0) |
| 42 | + # Define a fixture |
| 43 | + fd = FixtureDef.new |
| 44 | + fd.shape = cs |
| 45 | + # For filtering out collisions |
| 46 | + #fd.filter.groupIndex = -2 |
| 47 | + # Parameters that affect physics |
| 48 | + fd.set_density(0.1) |
| 49 | + fd.set_restitution(0.05) |
| 50 | + fd.set_friction(1.0) |
| 51 | + # Finalize the body |
| 52 | + body.create_fixture(fd) |
| 53 | + # Add it to the volume |
| 54 | + cvjd.add_body(body) |
| 55 | + # Store our own copy for later rendering |
| 56 | + outline << body |
| 57 | + end |
| 58 | + # These parameters control how stiff vs. jiggly the blob is |
| 59 | + cvjd.frequencyHz = 10.0 |
| 60 | + cvjd.dampingRatio = 3.0 |
| 61 | + # Put the joint thing in our world! |
| 62 | + box2d.world.create_joint(cvjd) |
| 63 | + end |
| 64 | + |
| 65 | + # Time to draw the blob! |
| 66 | + # Can you make it a cute character, a la |
| 67 | + # http://postspectacular.com/work/nokia/friends/start |
| 68 | + def display |
| 69 | + # Draw the outline |
| 70 | + begin_shape |
| 71 | + fill(hue) |
| 72 | + stroke(0, 0, 255) |
| 73 | + stroke_weight(0) |
| 74 | + outline.each do |b| |
| 75 | + pos = box2d.body_coord(b) |
| 76 | + vertex(pos.x, pos.y) |
| 77 | + end |
| 78 | + end_shape(CLOSE) |
| 79 | + end |
| 80 | +end |
0 commit comments