|
| 1 | +# The Nature of Code |
| 2 | +# Daniel Shiffman |
| 3 | +# http://natureofcode.com |
| 4 | + |
| 5 | +# A rectangular box |
| 6 | +class Box |
| 7 | + extend Forwardable |
| 8 | + def_delegators(:@app, :fill, :stroke, :stroke_weight, :rect, :rect_mode, |
| 9 | + :box2d, :rotate, :translate, :push_matrix, :pop_matrix) |
| 10 | + # We need to keep track of a Body and a width and height |
| 11 | + attr_accessor :body, :w, :h |
| 12 | + # Constructor |
| 13 | + def initialize(x, y) |
| 14 | + @app = $app |
| 15 | + @w, @h = 24, 24 |
| 16 | + # Add the box to the box2d world |
| 17 | + make_body(Vec2.new(x, y), w, h) |
| 18 | + end |
| 19 | + |
| 20 | + # This function removes the particle from the box2d world |
| 21 | + def kill_body |
| 22 | + box2d.destroy_body(body) |
| 23 | + end |
| 24 | + |
| 25 | + def contains(x, y) |
| 26 | + world_point = box2d.processing_to_world(x, y) |
| 27 | + f = body.get_fixture_list |
| 28 | + f.test_point(world_point) |
| 29 | + end |
| 30 | + |
| 31 | + # Drawing the box |
| 32 | + def display |
| 33 | + # We look at each body and get its screen position |
| 34 | + pos = box2d.body_coord(body) |
| 35 | + # Get its angle of rotation |
| 36 | + a = body.getAngle |
| 37 | + rect_mode(Java::ProcessingCore::PConstants::CENTER) |
| 38 | + push_matrix |
| 39 | + translate(pos.x, pos.y) |
| 40 | + rotate(a) |
| 41 | + fill(127) |
| 42 | + stroke(0) |
| 43 | + stroke_weight(2) |
| 44 | + rect(0, 0, w, h) |
| 45 | + pop_matrix |
| 46 | + end |
| 47 | + |
| 48 | + # This function adds the rectangle to the box2d world |
| 49 | + def make_body(center, w, h) |
| 50 | + # Define and create the body |
| 51 | + bd = BodyDef.new |
| 52 | + bd.type = BodyType::DYNAMIC |
| 53 | + bd.position.set(box2d.processing_to_world(center)) |
| 54 | + @body = box2d.createBody(bd) |
| 55 | + # Define a polygon (this is what we use for a rectangle) |
| 56 | + sd = PolygonShape.new |
| 57 | + box2dw = box2d.scale_to_world(w / 2) |
| 58 | + box2dh = box2d.scale_to_world(h / 2) |
| 59 | + sd.setAsBox(box2dw, box2dh) |
| 60 | + # Define a fixture |
| 61 | + fd = FixtureDef.new |
| 62 | + fd.shape = sd |
| 63 | + # Parameters that affect physics |
| 64 | + fd.density = 1 |
| 65 | + fd.friction = 0.3 |
| 66 | + fd.restitution = 0.5 |
| 67 | + body.create_fixture(fd) |
| 68 | + # Give it some initial random velocity |
| 69 | + body.set_linear_velocity(Vec2.new(rand(-5.0..5), rand(2.0..5))) |
| 70 | + body.set_angular_velocity(rand(-5.0..5)) |
| 71 | + end |
| 72 | +end |
0 commit comments