I'm just starting with chipmunk, trying to integrate it into my little 2D rendering engine.
At the moment, i've got 2 Shape::Polys, one rectangle at 'ground level', and another created above it. The ground one is added to the world as a shape only to stop it moving, and gravity drops the second towards it.
As the two shapes intersect, the collision callback is raised appropriately, but nothing happens - the shape keeps falling as if nothing touched it.
anyway, code!
This bit manages a collection of objects:
Code: Select all
class PhysicsManager
def initialize(engine)
puts "Todo: Fix timing for physics"
#Copy engine reference
@engine=engine
#Create the physical world
@space = CP::Space.new
@space.damping=0.9
@space.gravity=CP::Vec2.new(0,1)
@space.iterations=10
@objects = []
#Add a default collision handler
@space.add_collision_func(:Object, :Object) do |a, b|
puts "Collision!"
true
end
#Listen for time updates
@lastDelta=0
@engine.addListener (self, TimeEvent)
testAdd
end
#Move the simulation forward
def tick()
#For each object, copy current position into physics sim
@objects.each do |o|
#o.posFromSceneObj
end
#Advance the phyiscs
@space.step(@lastDelta/60.0)
#Move physics position back into object
@objects.each do |o|
o.posToSceneObj
end
end
#Adds an object to the simulation
def addObject(obj,static)
@objects[@objects.length]=obj
#Only add body to simulation if it is non-static
if (!static) then
@space.add_body(obj.body)
#Add shape to simulation
@space.add_shape(obj.shape)
else
puts "todo: @space.add_static_shape?"
@space.add_shape(obj.shape)
end
end
Code: Select all
class NewSquare
attr_accessor :body
attr_accessor :shape
def initialize
@body=nil
@shape=nil
@position=nil
end
#Called by a SceneObject to tether the position fields together
def attachPosition(pos)
#Copy the reference
@position=pos
#We can now create the object
@body = CP::Body.new(1,1)
@body.p = CP::Vec2.new(@position.position[0],@position.position[1])
@body.v = CP::Vec2.new(0, 0)
@body.a = (2*Math::PI/2.0)
#Shape corners
x1 = -(@position.size[0] / 2.0)
x2 = -x1
y1 = -(@position.size[1] / 2.0)
y2 = -y1
@shape_verts = [CP::Vec2.new(x1, y2),CP::Vec2.new(x2, y2),CP::Vec2.new(x2, y1),CP::Vec2.new(x1, y1)]
#Create shape
@shape = CP::Shape::Poly.new(@body,@shape_verts,CP::Vec2.new(0,0))
@shape.u=1
@shape.collision_type=:Object
#Steal the object's position
posFromSceneObj()
end
def posFromSceneObj
@body.p = CP::Vec2.new(@position.position[0] + 0.5 * @position.size[0],@position.position[1] + 0.5 * @position.size[1])
@body.a = @position.angle
end
#Copy the position from the physics object -> scene object
def posToSceneObj
@position.position[0] = @body.p.x - 0.5 * @position.size[0]
@position.position[1] = @body.p.y - 0.5 * @position.size[1]
@position.angle = @body.a
end
end
Any help would be great, this has had me stumped for a while now