Browse Source

New Urho2D sample demonstrating constraints.
Thanks to Aster for his help.

Mike3D 11 years ago
parent
commit
bba58e1287

+ 468 - 0
Bin/Data/LuaScripts/32_Urho2DConstraints.lua

@@ -0,0 +1,468 @@
+-- Urho2D physics Constraints sample.
+-- This sample is designed to help understanding and chosing the right constraint.
+-- This sample demonstrates:
+--      - Creating physics constraints
+--      - Creating Edge and Polygon Shapes from vertices
+--      - Displaying physics debug geometry and constraints' joints
+--      - Using SetOrderInLayer to alter the way sprites are drawn in relation to each other
+--      - Using Text3D to display some text affected by zoom
+--      - Setting the background color for the scene
+
+require "LuaScripts/Utilities/Sample"
+
+local camera = nil
+local physicsWorld = nil
+local pickedNode = nil
+local dummyBody = nil
+
+function Start()
+    SampleStart()
+    CreateScene()
+    input.mouseVisible = true -- Show mouse cursor
+    CreateInstructions()
+    SubscribeToEvents()
+end
+
+function CreateScene()
+    scene_ = Scene()
+    scene_:CreateComponent("Octree")
+    scene_:CreateComponent("DebugRenderer")
+    physicsWorld = scene_:CreateComponent("PhysicsWorld2D")
+    physicsWorld.drawJoint = true -- Display the joints (Note that DrawDebugGeometry() must be set to true to acually draw the joints)
+    drawDebug = true -- Set DrawDebugGeometry() to true
+
+    -- Create camera
+    cameraNode = scene_:CreateChild("Camera")
+    cameraNode.position = Vector3(0, 0, 0) -- Note that Z setting is discarded; use camera.zoom instead (see MoveCamera() below for example)
+    camera = cameraNode:CreateComponent("Camera")
+    camera.orthographic = true
+    camera.orthoSize = graphics.height * PIXEL_SIZE
+    camera.zoom = 1.2
+    renderer:SetViewport(0, Viewport:new(scene_, camera))
+    renderer.defaultZone.fogColor = Color(0.1, 0.1, 0.1) -- Set background color for the scene
+
+    -- Create a 4x3 grid
+    for i=0, 4 do
+        local edgeNode = scene_:CreateChild("VerticalEdge")
+        local edgeBody = edgeNode:CreateComponent("RigidBody2D")
+        if dummyBody == nil then dummyBody = edgeBody end -- Mark first edge as dummy body (used by mouse pick)
+        local edgeShape = edgeNode:CreateComponent("CollisionEdge2D")
+        edgeShape:SetVertices(Vector2(i*2.5 -5, -3), Vector2(i*2.5 -5, 3))
+        edgeShape.friction = 0.5 -- Set friction
+    end
+
+    for j=0, 3 do
+        local edgeNode = scene_:CreateChild("HorizontalEdge")
+        local edgeBody = edgeNode:CreateComponent("RigidBody2D")
+        local edgeShape = edgeNode:CreateComponent("CollisionEdge2D")
+        edgeShape:SetVertices(Vector2(-5, j*2 -3), Vector2(5, j*2 -3))
+        edgeShape.friction = 0.5 -- Set friction
+    end
+
+    -- Create a box (will be cloned later)
+    local box  = scene_:CreateChild("Box")
+    box.position = Vector3(0.8, -2, 0)
+    local staticSprite = box:CreateComponent("StaticSprite2D")
+    staticSprite.sprite = cache:GetResource("Sprite2D", "Urho2D/Box.png")
+    local body = box:CreateComponent("RigidBody2D")
+    body.bodyType = BT_DYNAMIC
+    body.linearDamping = 0
+    body.angularDamping  = 0
+    local shape = box:CreateComponent("CollisionBox2D") -- Create box shape
+    shape.size = Vector2(0.32, 0.32) -- Set size
+    shape.density = 1 -- Set shape density (kilograms per meter squared)
+    shape.friction = 0.5 -- Set friction
+    shape.restitution = 0.1 -- Set restitution (slight bounce)
+
+    -- Create a ball (will be cloned later)
+    local ball  = scene_:CreateChild("Ball")
+    ball.position = Vector3(1.8, -2, 0)
+    local staticSprite = ball:CreateComponent("StaticSprite2D")
+    staticSprite.sprite = cache:GetResource("Sprite2D", "Urho2D/Ball.png")
+    local body = ball:CreateComponent("RigidBody2D")
+    body.bodyType = BT_DYNAMIC
+    body.linearDamping = 0
+    body.angularDamping  = 0
+    local shape = ball:CreateComponent("CollisionCircle2D") -- Create circle shape
+    shape.radius = 0.16 -- Set radius
+    shape.density = 1 -- Set shape density (kilograms per meter squared)
+    shape.friction = 0.5 -- Set friction
+    shape.restitution = 0.6 -- Set restitution: make it bounce
+
+    -- Create a polygon
+    local node = scene_:CreateChild("Polygon")
+    node.position = Vector3(1.6, -2, 0)
+    node:SetScale(0.7)
+    local staticSprite = node:CreateComponent("StaticSprite2D")
+    staticSprite.sprite = cache:GetResource("Sprite2D", "Urho2D/Aster.png")
+    local body = node:CreateComponent("RigidBody2D")
+    body.bodyType = BT_DYNAMIC
+    local shape = node:CreateComponent("CollisionPolygon2D")
+    shape:SetVertices{Vector2(-0.8, -0.3), Vector2(0.5, -0.8), Vector2(0.8, -0.3), Vector2(0.8, 0.5), Vector2(0.5, 0.9), Vector2(-0.5, 0.7)}
+    shape.density = 1 -- Set shape density (kilograms per meter squared)
+    shape.friction = 0.3 -- Set friction
+    shape.restitution = 0 -- Set restitution (no bounce)
+
+    -- Create a ConstraintDistance2D
+    CreateFlag("ConstraintDistance2D", -4.97, 3) -- Display Text3D flag
+    local boxNode = box:Clone()
+    local ballNode = ball:Clone()
+    local ballBody = ballNode:GetComponent("RigidBody2D")
+    boxNode.position = Vector3(-4.5, 2, 0)
+    ballNode.position = Vector3(-3, 2, 0)
+
+    local constraintDistance = boxNode:CreateComponent("ConstraintDistance2D") -- Apply ConstraintDistance2D to box
+    constraintDistance.otherBody = ballBody -- Constrain ball to box
+    constraintDistance.ownerBodyAnchor = boxNode.position
+    constraintDistance.otherBodyAnchor = ballNode.position
+    -- Make the constraint soft (comment to make it rigid, which is its basic behavior)
+    constraintDistance.frequencyHz = 4
+    constraintDistance.dampingRatio = 0.5
+
+    -- Create a ConstraintFriction2D ********** Not functional. From Box2d samples it seems that 2 anchors are required, Urho2D only provides 1, needs investigation ***********
+    CreateFlag("ConstraintFriction2D", 0.03, 1) -- Display Text3D flag
+    local boxNode = box:Clone()
+    local ballNode = ball:Clone()
+    boxNode.position = Vector3(0.5, 0, 0)
+    ballNode.position = Vector3(1.5, 0, 0)
+
+    local constraintFriction = boxNode:CreateComponent("ConstraintFriction2D") -- Apply ConstraintDistance2D to box
+    constraintFriction.otherBody = ballNode:GetComponent("RigidBody2D") -- Constraint ball to box
+    constraintFriction.ownerBodyAnchor = boxNode.position
+    --constraintFriction.otherBodyAnchor = ballNode.position
+    --constraintFriction.maxForce = 10 -- ballBody.mass * gravity
+    --constraintDistance.maxTorque = 10 -- ballBody.mass * radius * gravity
+
+    -- Create a ConstraintGear2D
+    CreateFlag("ConstraintGear2D", -4.97, -1) -- Display Text3D flag
+    local baseNode = box:Clone()
+    baseNode:GetComponent("RigidBody2D").bodyType = BT_STATIC
+    baseNode.position = Vector3(-3.7, -2.5, 0)
+    local ball1Node = ball:Clone()
+    ball1Node.position = Vector3(-4.5, -2, 0)
+    local ball1Body = ball1Node:GetComponent("RigidBody2D")
+    local ball2Node = ball:Clone()
+    ball2Node.position = Vector3(-3, -2, 0)
+    local ball2Body = ball2Node:GetComponent("RigidBody2D")
+
+    local gear1 = baseNode:CreateComponent("ConstraintRevolute2D") -- Apply constraint to baseBox
+    gear1.otherBody = ball1Body -- Constrain ball1 to baseBox
+    gear1.anchor = ball1Node.position
+    local gear2 = baseNode:CreateComponent("ConstraintRevolute2D") -- Apply constraint to baseBox
+    gear2.otherBody = ball2Body -- Constrain ball2 to baseBox
+    gear2.anchor = ball2Node.position
+
+    local constraintGear = ball1Node:CreateComponent("ConstraintGear2D") -- Apply constraint to ball1
+    constraintGear.otherBody = ball2Body -- Constrain ball2 to ball1
+    constraintGear.ownerConstraint = gear1
+    constraintGear.otherConstraint = gear2
+    constraintGear.ratio=1
+
+    ball1Body:ApplyAngularImpulse(0.015) -- Animate
+
+    -- Create a vehicle from a compound of 2 ConstraintWheel2Ds
+    CreateFlag("ConstraintWheel2Ds compound", -2.45, -1) -- Display Text3D flag
+    local car = box:Clone()
+    car.scale = Vector3(4, 1, 0)
+    car.position = Vector3(-1.2, -2.3, 0)
+    car:GetComponent("StaticSprite2D").orderInLayer = 0 -- Draw car on top of the wheels (set to -1 to draw below)
+    local ball1Node = ball:Clone()
+    ball1Node.position = Vector3(-1.6, -2.5, 0)
+    local ball2Node = ball:Clone()
+    ball2Node.position = Vector3(-0.8, -2.5, 0)
+
+    local wheel1 = car:CreateComponent("ConstraintWheel2D")
+    wheel1.otherBody = ball1Node:GetComponent("RigidBody2D")
+    wheel1.anchor = ball1Node.position
+    wheel1.axis = Vector2(0, 1)
+    wheel1.maxMotorTorque = 20
+    wheel1.frequencyHz = 4
+    wheel1.dampingRatio = 0.4
+
+    local wheel2 = car:CreateComponent("ConstraintWheel2D")
+    wheel2.otherBody = ball2Node:GetComponent("RigidBody2D")
+    wheel2.anchor = ball2Node.position
+    wheel2.axis = Vector2(0, 1)
+    wheel2.maxMotorTorque = 10
+    wheel2.frequencyHz = 4
+    wheel2.dampingRatio = 0.4
+
+    -- Create a ConstraintMotor2D
+    CreateFlag("ConstraintMotor2D", 2.53, -1) -- Display Text3D flag
+    local boxNode = box:Clone()
+    boxNode:GetComponent("RigidBody2D").bodyType = BT_STATIC
+    local ballNode = ball:Clone()
+    boxNode.position = Vector3(3.8, -2.1, 0)
+    ballNode.position = Vector3(3.8, -1.5, 0)
+
+    constraintMotor = boxNode:CreateComponent("ConstraintMotor2D")
+    constraintMotor.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
+    constraintMotor.linearOffset = Vector2(0, 0.8) -- Set ballNode position relative to boxNode position = (0,0)
+    constraintMotor.angularOffset = 0.1
+    constraintMotor.maxForce = 5
+    constraintMotor.maxTorque = 10
+    constraintMotor.correctionFactor = 1
+    constraintMotor.collideConnected = true -- doesn't work
+
+    -- Create a ConstraintMouse2D is demonstrated in HandleMouseButtonDown() function. It is used to "grasp" the sprites with the mouse.
+    CreateFlag("ConstraintMouse2D", 0.03, -1) -- Display Text3D flag
+
+    -- Create a ConstraintPrismatic2D
+    CreateFlag("ConstraintPrismatic2D", 2.53, 3) -- Display Text3D flag
+    local boxNode = box:Clone()
+    boxNode:GetComponent("RigidBody2D").bodyType = BT_STATIC
+    local ballNode = ball:Clone()
+    boxNode.position = Vector3(3.3, 2.5, 0)
+    ballNode.position = Vector3(4.3, 2, 0)
+
+    local constraintPrismatic = boxNode:CreateComponent("ConstraintPrismatic2D")
+    constraintPrismatic.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
+    constraintPrismatic.axis = Vector2(1, 1) -- Slide from [0,0] to [1,1]
+    constraintPrismatic.anchor = Vector2(4, 2)
+    constraintPrismatic.lowerTranslation = -1
+    constraintPrismatic.upperTranslation = 0.5
+    constraintPrismatic.enableLimit = true
+    constraintPrismatic.maxMotorForce = 1
+    constraintPrismatic.motorSpeed = 0
+
+    -- Create a ConstraintPulley2D
+    CreateFlag("ConstraintPulley2D", 0.03, 3) -- Display Text3D flag
+    local boxNode = box:Clone()
+    local ballNode = ball:Clone()
+    boxNode.position = Vector3(0.5, 2, 0)
+    ballNode.position = Vector3(2, 2, 0)
+
+    local constraintPulley = boxNode:CreateComponent("ConstraintPulley2D") -- Apply constraint to box
+    constraintPulley.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
+    constraintPulley.ownerBodyAnchor = boxNode.position
+    constraintPulley.otherBodyAnchor = ballNode.position
+    constraintPulley.ownerBodyGroundAnchor = Vector2(boxNode.position.x, boxNode.position.y + 1)
+    constraintPulley.otherBodyGroundAnchor = Vector2(ballNode.position.x, ballNode.position.y + 1)
+    constraintPulley.ratio = 1 -- Weight ratio between ownerBody and otherBody
+
+    -- Create a ConstraintRevolute2D
+    CreateFlag("ConstraintRevolute2D", -2.45, 3) -- Display Text3D flag
+    local boxNode = box:Clone()
+    boxNode:GetComponent("RigidBody2D").bodyType = BT_STATIC
+    local ballNode = ball:Clone()
+    boxNode.position = Vector3(-2, 1.5, 0)
+    ballNode.position = Vector3(-1, 2, 0)
+
+    local constraintRevolute = boxNode:CreateComponent("ConstraintRevolute2D") -- Apply constraint to box
+    constraintRevolute.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
+    constraintRevolute.anchor = Vector2(-1, 1.5)
+    constraintRevolute.lowerAngle = -1 -- In radians
+    constraintRevolute.upperAngle = 0.5 -- In radians
+    constraintRevolute.enableLimit = true
+    constraintRevolute.maxMotorTorque = 10
+    constraintRevolute.motorSpeed = 0
+    constraintRevolute.enableMotor = true
+
+    -- Create a ConstraintRope2D
+    CreateFlag("ConstraintRope2D", -4.97, 1) -- Display Text3D flag
+    local boxNode = box:Clone()
+    boxNode:GetComponent("RigidBody2D").bodyType = BT_STATIC
+    local ballNode = ball:Clone()
+    boxNode.position = Vector3(-3.7, 0.7, 0)
+    ballNode.position = Vector3(-4.5, 0, 0)
+
+    local constraintRope = boxNode:CreateComponent("ConstraintRope2D")
+    constraintRope.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
+    constraintRope.ownerBodyAnchor = Vector2(0, -0.5) -- Offset from box (OwnerBody) : the rope is rigid from OwnerBody center to this ownerBodyAnchor
+    constraintRope.maxLength = 0.9 -- Rope length
+    constraintRope.collideConnected = true
+
+    -- Create a ConstraintWeld2D
+    CreateFlag("ConstraintWeld2D", -2.45, 1) -- Display Text3D flag
+    local boxNode = box:Clone()
+    local ballNode = ball:Clone()
+    boxNode.position = Vector3(-0.5, 0, 0)
+    ballNode.position = Vector3(-2, 0, 0)
+
+    local constraintWeld = boxNode:CreateComponent("ConstraintWeld2D")
+    constraintWeld.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
+    constraintWeld.anchor = boxNode.position
+    constraintWeld.frequencyHz = 4
+    constraintWeld.dampingRatio = 0.5
+
+    -- ConstraintWheel2D
+    CreateFlag("ConstraintWheel2D",  2.53, 1) -- Display Text3D flag
+    local boxNode = box:Clone()
+    local ballNode = ball:Clone()
+    boxNode.position = Vector3(3.8, 0, 0)
+    ballNode.position = Vector3(3.8, 0.9, 0)
+
+    local constraintWheel = boxNode:CreateComponent("ConstraintWheel2D")
+    constraintWheel.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
+    constraintWheel.anchor = ballNode.position
+    constraintWheel.axis = Vector2(0, 1)
+    constraintWheel.enableMotor = true
+    constraintWheel.maxMotorTorque = 1
+    constraintWheel.motorSpeed = 0
+    constraintWheel.frequencyHz = 4
+    constraintWheel.dampingRatio = 0.5
+    constraintWheel.collideConnected = true -- doesn't work
+end
+
+function CreateFlag(text, x, y) -- Used to create Tex3D flags
+    local flagNode = scene_:CreateChild("Flag")
+    flagNode.position = Vector3(x, y, 0)
+    local flag3D = flagNode:CreateComponent("Text3D") -- We use Text3D in order to make the text affected by zoom (so that it sticks to 2D)
+    flag3D.text = text
+    flag3D:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
+end
+
+function CreateInstructions()
+    -- Construct new Text object, set string to display and font to use
+    local instructionText = ui.root:CreateChild("Text")
+    instructionText:SetText("Use WASD keys and mouse to move, Use PageUp PageDown to zoom.\n Space to toggle debug geometry and joints - F5 to save the scene.")
+    instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
+    instructionText.textAlignment = HA_CENTER -- Center rows in relation to each other
+
+    -- Position the text relative to the screen center
+    instructionText.horizontalAlignment = HA_CENTER
+    instructionText.verticalAlignment = VA_CENTER
+
+    instructionText:SetPosition(0, ui.root.height / 4)
+end
+
+function MoveCamera(timeStep)
+    if ui.focusElement ~= nil then return end -- Do not move if the UI has a focused element (the console)
+
+    local MOVE_SPEED = 4 -- Movement speed as world units per second
+
+    -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
+    if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0, 1, 0) * MOVE_SPEED * timeStep) end
+    if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0, -1, 0) * MOVE_SPEED * timeStep) end
+    if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1, 0, 0) * MOVE_SPEED * timeStep) end
+    if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1, 0, 0) * MOVE_SPEED * timeStep) end
+
+    if input:GetKeyDown(KEY_PAGEUP) then camera.zoom = camera.zoom * 1.01 end -- Zoom In
+    if input:GetKeyDown(KEY_PAGEDOWN) then camera.zoom = camera.zoom * 0.99 end -- Zoom Out
+end
+
+function SubscribeToEvents()
+    SubscribeToEvent("Update", "HandleUpdate")
+    SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
+    SubscribeToEvent("MouseButtonDown", "HandleMouseButtonDown")
+    if touchEnabled then SubscribeToEvent("TouchBegin", "HandleTouchBegin3") end
+    -- Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
+    UnsubscribeFromEvent("SceneUpdate")
+end
+
+function HandleUpdate(eventType, eventData)
+    local timestep = eventData:GetFloat("TimeStep")
+    MoveCamera(timestep) -- Move the camera according to frame's time step
+    if input:GetKeyPress(KEY_SPACE) then drawDebug = not drawDebug end -- Toggle debug geometry with space
+    if input:GetKeyPress(KEY_F5) then scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/Constraints.xml") end -- Save scene
+end
+
+function HandlePostRenderUpdate(eventType, eventData)
+    if drawDebug then physicsWorld:DrawDebugGeometry(true) end
+end
+
+function HandleMouseButtonDown(eventType, eventData)
+    local rigidBody = physicsWorld:GetRigidBody(input.mousePosition.x, input.mousePosition.y) -- Raycast for RigidBody2Ds to pick
+    if rigidBody ~= nil then
+        pickedNode = rigidBody:GetNode()
+        local staticSprite = pickedNode:GetComponent("StaticSprite2D")
+        staticSprite.color = Color(1, 0, 0, 1) -- Temporary modify color of the picked sprite
+
+        -- ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with the mouse
+        local constraintMouse = pickedNode:CreateComponent("ConstraintMouse2D")
+        constraintMouse.target = GetMousePositionXY()
+        constraintMouse.maxForce = 1000 * rigidBody.mass
+        constraintMouse.collideConnected = true
+        constraintMouse.otherBody = dummyBody  -- Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
+        constraintMouse.dampingRatio = 0
+    end
+    SubscribeToEvent("MouseMove", "HandleMouseMove")
+    SubscribeToEvent("MouseButtonUp", "HandleMouseButtonUp")
+end
+
+function HandleMouseButtonUp(eventType, eventData)
+    if pickedNode ~= nil then
+        local staticSprite = pickedNode:GetComponent("StaticSprite2D")
+        staticSprite.color = Color(1, 1, 1, 1) -- Restore picked sprite color
+
+        pickedNode:RemoveComponent("ConstraintMouse2D") -- Remove temporary constraint
+        pickedNode = nil
+    end
+    UnsubscribeFromEvent("MouseMove")
+    UnsubscribeFromEvent("MouseButtonUp")
+end
+
+function GetMousePositionXY()
+    local screenPoint = Vector3(input.mousePosition.x / graphics.width, input.mousePosition.y / graphics.height, 0)
+    local worldPoint = camera:ScreenToWorldPoint(screenPoint)
+    return Vector2(worldPoint.x, worldPoint.y)
+end
+
+function HandleMouseMove(eventType, eventData)
+    if pickedNode ~= nil then
+        local constraintMouse = pickedNode:GetComponent("ConstraintMouse2D")
+        constraintMouse.target = GetMousePositionXY()
+    end
+end
+
+function HandleTouchBegin3(eventType, eventData)
+    local rigidBody = physicsWorld:GetRigidBody(eventData:GetInt("X"), eventData:GetInt("Y")) -- Raycast for RigidBody2Ds to pick
+    if rigidBody ~= nil then
+        pickedNode = rigidBody:GetNode()
+        local staticSprite = pickedNode:GetComponent("StaticSprite2D")
+        staticSprite.color = Color(1, 0, 0, 1) -- Temporary modify color of the picked sprite
+        local rigidBody = pickedNode:GetComponent("RigidBody2D")
+
+        -- ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with touch
+        local constraintMouse = pickedNode:CreateComponent("ConstraintMouse2D")
+        constraintMouse.target = camera:ScreenToWorldPoint(Vector3(eventData:GetInt("X") / graphics.width, eventData:GetInt("Y") / graphics.height, 0))
+        constraintMouse.maxForce = 1000 * rigidBody.mass
+        constraintMouse.collideConnected = true
+        constraintMouse.otherBody = dummyBody  -- Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
+        constraintMouse.dampingRatio = 0
+    end
+    SubscribeToEvent("TouchMove", "HandleTouchMove3")
+    SubscribeToEvent("TouchEnd", "HandleTouchEnd3")
+end
+
+function HandleTouchMove3(eventType, eventData)
+    if pickedNode ~= nil then
+        local constraintMouse = pickedNode:GetComponent("ConstraintMouse2D")
+        constraintMouse.target = camera:ScreenToWorldPoint(Vector3(eventData:GetInt("X") / graphics.width, eventData:GetInt("Y") / graphics.height, 0))
+    end
+end
+
+function HandleTouchEnd3(eventType, eventData)
+    if pickedNode ~= nil then
+        local staticSprite = pickedNode:GetComponent("StaticSprite2D")
+        staticSprite.color = Color(1, 1, 1, 1) -- Restore picked sprite color
+
+        pickedNode:RemoveComponent("ConstraintMouse2D") -- Remove temporary constraint
+        pickedNode = nil
+    end
+    UnsubscribeFromEvent("TouchMove")
+    UnsubscribeFromEvent("TouchEnd")
+end
+
+-- Create XML patch instructions for screen joystick layout specific to this sample app
+function GetScreenJoystickPatchString()
+    return
+        "<patch>" ..
+        "    <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
+        "    <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" ..
+        "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
+        "        <element type=\"Text\">" ..
+        "            <attribute name=\"Name\" value=\"KeyBinding\" />" ..
+        "            <attribute name=\"Text\" value=\"PAGEUP\" />" ..
+        "        </element>" ..
+        "    </add>" ..
+        "    <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
+        "    <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" ..
+        "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
+        "        <element type=\"Text\">" ..
+        "            <attribute name=\"Name\" value=\"KeyBinding\" />" ..
+        "            <attribute name=\"Text\" value=\"PAGEDOWN\" />" ..
+        "        </element>" ..
+        "    </add>" ..
+        "</patch>"
+end

+ 509 - 0
Bin/Data/Scripts/32_Urho2DConstraints.as

@@ -0,0 +1,509 @@
+// Urho2D physics Constraints sample.
+// This sample is designed to help understanding and chosing the right constraint.
+// This sample demonstrates:
+//      - Creating physics constraints
+//      - Creating Edge and Polygon Shapes from vertices
+//      - Displaying physics debug geometry and constraints' joints
+//      - Using SetOrderInLayer to alter the way sprites are drawn in relation to each other
+//      - Using Text3D to display some text affected by zoom
+//      - Setting the background color for the scene
+
+#include "Scripts/Utilities/Sample.as"
+
+Camera@ camera;
+Node@ pickedNode;
+RigidBody2D@ dummyBody;
+
+void Start()
+{
+    SampleStart();
+    CreateScene();
+    input.mouseVisible = true; // Show mouse cursor
+    CreateInstructions();
+    SubscribeToEvents();
+}
+
+void CreateScene()
+{
+    scene_ = Scene();
+    scene_.CreateComponent("Octree");
+    scene_.CreateComponent("DebugRenderer");
+    PhysicsWorld2D@ physicsWorld = scene_.CreateComponent("PhysicsWorld2D");
+    physicsWorld.drawJoint = true; // Display the joints (Note that DrawDebugGeometry() must be set to true to acually draw the joints)
+    drawDebug = true; // Set DrawDebugGeometry() to true
+
+    // Create camera
+    cameraNode = scene_.CreateChild("Camera");
+    cameraNode.position = Vector3(0.0f, 0.0f, 0.0f); // Note that Z setting is discarded; use camera.zoom instead (see MoveCamera() below for example)
+    camera = cameraNode.CreateComponent("Camera");
+    camera.orthographic = true;
+    camera.orthoSize = graphics.height * PIXEL_SIZE;
+    camera.zoom = 1.2f;
+    renderer.viewports[0] = Viewport(scene_, camera);
+    renderer.defaultZone.fogColor = Color(0.1f, 0.1f, 0.1f); // Set background color for the scene
+
+    // Create 4x3 grid
+    for (uint i = 0; i<5; ++i)
+    {
+        Node@ edgeNode = scene_.CreateChild("VerticalEdge");
+        RigidBody2D@ edgeBody = edgeNode.CreateComponent("RigidBody2D");
+        if (dummyBody is null)
+            dummyBody = edgeBody; // Mark first edge as dummy body (used by mouse pick)
+        CollisionEdge2D@ edgeShape = edgeNode.CreateComponent("CollisionEdge2D");
+        edgeShape.SetVertices(Vector2(i*2.5f -5.0f, -3.0f), Vector2(i*2.5f -5.0f, 3.0f));
+        edgeShape.friction = 0.5f; // Set friction
+    }
+
+    for (uint j = 0; j<4; ++j)
+    {
+        Node@ edgeNode = scene_.CreateChild("HorizontalEdge");
+        RigidBody2D@ edgeBody = edgeNode.CreateComponent("RigidBody2D");
+        CollisionEdge2D@ edgeShape = edgeNode.CreateComponent("CollisionEdge2D");
+        edgeShape.SetVertices(Vector2(-5.0f, j*2.0f -3.0f), Vector2(5.0f, j*2.0f -3.0f));
+        edgeShape.friction = 0.5f; // Set friction
+    }
+
+    // Create a box (will be cloned later)
+    Node@ box  = scene_.CreateChild("Box");
+    box.position = Vector3(0.8f, -2.0f, 0.0f);
+    StaticSprite2D@ boxSprite = box.CreateComponent("StaticSprite2D");
+    boxSprite.sprite = cache.GetResource("Sprite2D", "Urho2D/Box.png");
+    RigidBody2D@ boxBody = box.CreateComponent("RigidBody2D");
+    boxBody.bodyType = BT_DYNAMIC;
+    boxBody.linearDamping = 0.0f;
+    boxBody.angularDamping  = 0.0f;
+    CollisionBox2D@ shape = box.CreateComponent("CollisionBox2D"); // Create box shape
+    shape.size = Vector2(0.32, 0.32); // Set size
+    shape.density = 1.0f; // Set shape density (kilograms per meter squared)
+    shape.friction = 0.5f; // Set friction
+    shape.restitution = 0.1f; // Set restitution (slight bounce)
+
+    // Create a ball (will be cloned later)
+    Node@ ball  = scene_.CreateChild("Ball");
+    ball.position = Vector3(1.8f, -2.0f, 0.0f);
+    StaticSprite2D@ ballSprite = ball.CreateComponent("StaticSprite2D");
+    ballSprite.sprite = cache.GetResource("Sprite2D", "Urho2D/Ball.png");
+    RigidBody2D@ ballBody = ball.CreateComponent("RigidBody2D");
+    ballBody.bodyType = BT_DYNAMIC;
+    ballBody.linearDamping = 0.0f;
+    ballBody.angularDamping  = 0.0f;
+    CollisionCircle2D@ ballShape = ball.CreateComponent("CollisionCircle2D"); // Create circle shape
+    ballShape.radius = 0.16f; // Set radius
+    ballShape.density = 1.0f; // Set shape density (kilograms per meter squared)
+    ballShape.friction = 0.5f; // Set friction
+    ballShape.restitution = 0.6f; // Set restitution: make it bounce
+
+    // Create a polygon
+    Node@ polygon = scene_.CreateChild("Polygon");
+    polygon.position = Vector3(1.6f, -2.0f, 0.0f);
+    polygon.SetScale(0.7f);
+    StaticSprite2D@ polygonSprite = polygon.CreateComponent("StaticSprite2D");
+    polygonSprite.sprite = cache.GetResource("Sprite2D", "Urho2D/Aster.png");
+    RigidBody2D@ polygonBody = polygon.CreateComponent("RigidBody2D");
+    polygonBody.bodyType = BT_DYNAMIC;
+    CollisionPolygon2D@ polygonShape = polygon.CreateComponent("CollisionPolygon2D");
+    Array<Vector2> polygonVertices = {Vector2(-0.8f, -0.3f), Vector2(0.5f, -0.8f), Vector2(0.8f, -0.3f), Vector2(0.8f, 0.5f), Vector2(0.5f, 0.9f), Vector2(-0.5f, 0.7f)};
+    polygonShape.SetVertices(polygonVertices);
+    polygonShape.density = 1.0f; // Set shape density (kilograms per meter squared)
+    polygonShape.friction = 0.3f; // Set friction
+    polygonShape.restitution = 0.0f; // Set restitution (no bounce)
+
+    // Create a ConstraintDistance2D
+    CreateFlag("ConstraintDistance2D", -4.97f, 3.0f); // Display Text3D flag
+    Node@ boxDistanceNode = box.Clone();
+    Node@ ballDistanceNode = ball.Clone();
+    RigidBody2D@ ballDistanceBody = ballDistanceNode.GetComponent("RigidBody2D");
+    boxDistanceNode.position = Vector3(-4.5f, 2.0f, 0.0f);
+    ballDistanceNode.position = Vector3(-3.0f, 2.0f, 0.0f);
+
+    ConstraintDistance2D@ constraintDistance = boxDistanceNode.CreateComponent("ConstraintDistance2D"); // Apply ConstraintDistance2D to box
+    constraintDistance.otherBody = ballDistanceBody; // Constrain ball to box
+    constraintDistance.ownerBodyAnchor = Vector2(boxDistanceNode.position.x, boxDistanceNode.position.y);
+    constraintDistance.otherBodyAnchor = Vector2(ballDistanceNode.position.x, ballDistanceNode.position.y);
+    // Make the constraint soft (comment to make it rigid, which is its basic behavior)
+    constraintDistance.frequencyHz = 4.0f;
+    constraintDistance.dampingRatio = 0.5f;
+
+    // Create a ConstraintFriction2D ********** Not functional. From Box2d samples it seems that 2 anchors are required, Urho2D only provides 1, needs investigation ***********
+    CreateFlag("ConstraintFriction2D", 0.03f, 1.0f); // Display Text3D flag
+    Node@ boxFrictionNode = box.Clone();
+    Node@ ballFrictionNode = ball.Clone();
+    boxFrictionNode.position = Vector3(0.5f, 0.0f, 0.0f);
+    ballFrictionNode.position = Vector3(1.5f, 0.0f, 0.0f);
+
+    ConstraintFriction2D@ constraintFriction = boxFrictionNode.CreateComponent("ConstraintFriction2D"); // Apply ConstraintDistance2D to box
+    constraintFriction.otherBody = ballFrictionNode.GetComponent("RigidBody2D"); // Constraint ball to box
+    //constraintFriction.ownerBodyAnchor = Vector2(boxNode.position.x, boxNode.position.y);
+    //constraintFriction.otherBodyAnchor = Vector2(ballNode.position.x, ballNode.position.y);
+    //constraintFriction.maxForce = 10.0f; // ballBody.mass * gravity
+    //constraintDistance.maxTorque = 10.0f; // ballBody.mass * radius * gravity
+
+    // Create a ConstraintGear2D
+    CreateFlag("ConstraintGear2D", -4.97f, -1.0f); // Display Text3D flag
+    Node@ baseNode = box.Clone();
+    RigidBody2D@ tempBody = baseNode.GetComponent("RigidBody2D"); // Get body to make it static
+    tempBody.bodyType = BT_STATIC;
+    baseNode.position = Vector3(-3.7f, -2.5f, 0.0f);
+    Node@ ball1Node = ball.Clone();
+    ball1Node.position = Vector3(-4.5f, -2.0f, 0.0f);
+    RigidBody2D@ ball1Body = ball1Node.GetComponent("RigidBody2D");
+    Node@ ball2Node = ball.Clone();
+    ball2Node.position = Vector3(-3.0f, -2.0f, 0.0f);
+    RigidBody2D@ ball2Body = ball2Node.GetComponent("RigidBody2D");
+
+    ConstraintRevolute2D@ gear1 = baseNode.CreateComponent("ConstraintRevolute2D"); // Apply constraint to baseBox
+    gear1.otherBody = ball1Body; // Constrain ball1 to baseBox
+    gear1.anchor = Vector2(ball1Node.position.x, ball1Node.position.y);
+    ConstraintRevolute2D@ gear2 = baseNode.CreateComponent("ConstraintRevolute2D"); // Apply constraint to baseBox
+    gear2.otherBody = ball2Body; // Constrain ball2 to baseBox
+    gear2.anchor = Vector2(ball2Node.position.x, ball2Node.position.y);
+
+    ConstraintGear2D@ constraintGear = ball1Node.CreateComponent("ConstraintGear2D"); // Apply constraint to ball1
+    constraintGear.otherBody = ball2Body; // Constrain ball2 to ball1
+    constraintGear.ownerConstraint = gear1;
+    constraintGear.otherConstraint = gear2;
+    constraintGear.ratio=1.0f;
+
+    ball1Body.ApplyAngularImpulse(0.015f, true); // Animate
+
+    // Create a vehicle from a compound of 2 ConstraintWheel2Ds
+    CreateFlag("ConstraintWheel2Ds compound", -2.45f, -1.0f); // Display Text3D flag
+    Node@ car = box.Clone();
+    car.scale = Vector3(4.0f, 1.0f, 0.0f);
+    car.position = Vector3(-1.2f, -2.3f, 0.0f);
+    StaticSprite2D@ tempSprite = car.GetComponent("StaticSprite2D"); // Get car Sprite in order to draw it on top
+    tempSprite.orderInLayer = 0; // Draw car on top of the wheels (set to -1 to draw below)
+    Node@ ball1WheelNode = ball.Clone();
+    ball1WheelNode.position = Vector3(-1.6f, -2.5f, 0.0f);
+    Node@ ball2WheelNode = ball.Clone();
+    ball2WheelNode.position = Vector3(-0.8f, -2.5f, 0.0f);
+
+    ConstraintWheel2D@ wheel1 = car.CreateComponent("ConstraintWheel2D");
+    wheel1.otherBody = ball1WheelNode.GetComponent("RigidBody2D");
+    wheel1.anchor = Vector2(ball1WheelNode.position.x, ball1WheelNode.position.y);
+    wheel1.axis = Vector2(0.0f, 1.0f);
+    wheel1.maxMotorTorque = 20.0f;
+    wheel1.frequencyHz = 4.0f;
+    wheel1.dampingRatio = 0.4f;
+
+    ConstraintWheel2D@ wheel2 = car.CreateComponent("ConstraintWheel2D");
+    wheel2.otherBody = ball2WheelNode.GetComponent("RigidBody2D");
+    wheel2.anchor = Vector2(ball2WheelNode.position.x, ball2WheelNode.position.y);
+    wheel2.axis = Vector2(0.0f, 1.0f);
+    wheel2.maxMotorTorque = 10.0f;
+    wheel2.frequencyHz = 4.0f;
+    wheel2.dampingRatio = 0.4f;
+
+    // ConstraintMotor2D
+    CreateFlag("ConstraintMotor2D", 2.53f, -1.0f); // Display Text3D flag
+    Node@ boxMotorNode = box.Clone();
+    tempBody = boxMotorNode.GetComponent("RigidBody2D"); // Get body to make it static
+    tempBody.bodyType = BT_STATIC;
+    Node@ ballMotorNode = ball.Clone();
+    boxMotorNode.position = Vector3(3.8f, -2.1f, 0.0f);
+    ballMotorNode.position = Vector3(3.8f, -1.5f, 0.0f);
+
+    ConstraintMotor2D@ constraintMotor = boxMotorNode.CreateComponent("ConstraintMotor2D");
+    constraintMotor.otherBody = ballMotorNode.GetComponent("RigidBody2D"); // Constrain ball to box
+    constraintMotor.linearOffset = Vector2(0.0f, 0.8f); // Set ballNode position relative to boxNode position = (0,0)
+    constraintMotor.angularOffset = 0.1f;
+    constraintMotor.maxForce = 5.0f;
+    constraintMotor.maxTorque = 10.0f;
+    constraintMotor.correctionFactor = 1.0f;
+    constraintMotor.collideConnected = true; // doesn't work
+
+    // ConstraintMouse2D is demonstrated in HandleMouseButtonDown() function. It is used to "grasp" the sprites with the mouse.
+    CreateFlag("ConstraintMouse2D", 0.03f, -1.0f); // Display Text3D flag
+
+    // Create a ConstraintPrismatic2D
+    CreateFlag("ConstraintPrismatic2D", 2.53f, 3.0f); // Display Text3D flag
+    Node@ boxPrismaticNode = box.Clone();
+    tempBody = boxPrismaticNode.GetComponent("RigidBody2D"); // Get body to make it static
+    tempBody.bodyType = BT_STATIC;
+    Node@ ballPrismaticNode = ball.Clone();
+    boxPrismaticNode.position = Vector3(3.3f, 2.5f, 0.0f);
+    ballPrismaticNode.position = Vector3(4.3f, 2.0f, 0.0f);
+
+    ConstraintPrismatic2D@ constraintPrismatic = boxPrismaticNode.CreateComponent("ConstraintPrismatic2D");
+    constraintPrismatic.otherBody = ballPrismaticNode.GetComponent("RigidBody2D"); // Constrain ball to box
+    constraintPrismatic.axis = Vector2(1.0f, 1.0f); // Slide from [0,0] to [1,1]
+    constraintPrismatic.anchor = Vector2(4.0f, 2.0f);
+    constraintPrismatic.lowerTranslation = -1.0f;
+    constraintPrismatic.upperTranslation = 0.5f;
+    constraintPrismatic.enableLimit = true;
+    constraintPrismatic.maxMotorForce = 1.0f;
+    constraintPrismatic.motorSpeed = 0.0f;
+
+    // ConstraintPulley2D
+    CreateFlag("ConstraintPulley2D", 0.03f, 3.0f); // Display Text3D flag
+    Node@ boxPulleyNode = box.Clone();
+    Node@ ballPulleyNode = ball.Clone();
+    boxPulleyNode.position = Vector3(0.5f, 2.0f, 0.0f);
+    ballPulleyNode.position = Vector3(2.0f, 2.0f, 0.0f);
+
+    ConstraintPulley2D@ constraintPulley = boxPulleyNode.CreateComponent("ConstraintPulley2D"); // Apply constraint to box
+    constraintPulley.otherBody = ballPulleyNode.GetComponent("RigidBody2D"); // Constrain ball to box
+    constraintPulley.ownerBodyAnchor = Vector2(boxPulleyNode.position.x, boxPulleyNode.position.y);
+    constraintPulley.otherBodyAnchor = Vector2(ballPulleyNode.position.x, ballPulleyNode.position.y);
+    constraintPulley.ownerBodyGroundAnchor = Vector2(boxPulleyNode.position.x, boxPulleyNode.position.y + 1);
+    constraintPulley.otherBodyGroundAnchor = Vector2(ballPulleyNode.position.x, ballPulleyNode.position.y + 1);
+    constraintPulley.ratio = 1.0; // Weight ratio between ownerBody and otherBody
+
+    // Create a ConstraintRevolute2D
+    CreateFlag("ConstraintRevolute2D", -2.45f, 3.0f); // Display Text3D flag
+    Node@ boxRevoluteNode = box.Clone();
+    tempBody = boxRevoluteNode.GetComponent("RigidBody2D"); // Get body to make it static
+    tempBody.bodyType = BT_STATIC;
+    Node@ ballRevoluteNode = ball.Clone();
+    boxRevoluteNode.position = Vector3(-2.0f, 1.5f, 0.0f);
+    ballRevoluteNode.position = Vector3(-1.0f, 2.0f, 0.0f);
+
+    ConstraintRevolute2D@ constraintRevolute = boxRevoluteNode.CreateComponent("ConstraintRevolute2D"); // Apply constraint to box
+    constraintRevolute.otherBody = ballRevoluteNode.GetComponent("RigidBody2D"); // Constrain ball to box
+    constraintRevolute.anchor = Vector2(-1.0f, 1.5f);
+    constraintRevolute.lowerAngle = -1.0f; // In radians
+    constraintRevolute.upperAngle = 0.5f; // In radians
+    constraintRevolute.enableLimit = true;
+    constraintRevolute.maxMotorTorque = 10.0f;
+    constraintRevolute.motorSpeed = 0.0f;
+    constraintRevolute.enableMotor = true;
+
+    // Create a ConstraintRope2D
+    CreateFlag("ConstraintRope2D", -4.97f, 1.0f); // Display Text3D flag
+    Node@ boxRopeNode = box.Clone();
+    tempBody = boxRopeNode.GetComponent("RigidBody2D");
+    tempBody.bodyType = BT_STATIC;
+    Node@ ballRopeNode = ball.Clone();
+    boxRopeNode.position = Vector3(-3.7f, 0.7f, 0.0f);
+    ballRopeNode.position = Vector3(-4.5f, 0.0f, 0.0f);
+
+    ConstraintRope2D@ constraintRope = boxRopeNode.CreateComponent("ConstraintRope2D");
+    constraintRope.otherBody = ballRopeNode.GetComponent("RigidBody2D"); // Constrain ball to box
+    constraintRope.ownerBodyAnchor = Vector2(0.0f, -0.5f); // Offset from box (OwnerBody) : the rope is rigid from OwnerBody center to this ownerBodyAnchor
+    constraintRope.maxLength = 0.9f; // Rope length
+    constraintRope.collideConnected = true;
+
+    // Create a ConstraintWeld2D
+    CreateFlag("ConstraintWeld2D", -2.45f, 1.0f); // Display Text3D flag
+    Node@ boxWeldNode = box.Clone();
+    Node@ ballWeldNode = ball.Clone();
+    boxWeldNode.position = Vector3(-0.5f, 0.0f, 0.0f);
+    ballWeldNode.position = Vector3(-2.0f, 0.0f, 0.0f);
+
+    ConstraintWeld2D@ constraintWeld = boxWeldNode.CreateComponent("ConstraintWeld2D");
+    constraintWeld.otherBody = ballWeldNode.GetComponent("RigidBody2D"); // Constrain ball to box
+    constraintWeld.anchor = Vector2(boxWeldNode.position.x, boxWeldNode.position.y);
+    constraintWeld.frequencyHz = 4.0f;
+    constraintWeld.dampingRatio = 0.5f;
+
+    // Create a ConstraintWheel2D
+    CreateFlag("ConstraintWheel2D",  2.53f, 1.0f); // Display Text3D flag
+    Node@ boxWheelNode = box.Clone();
+    Node@ ballWheelNode = ball.Clone();
+    boxWheelNode.position = Vector3(3.8f, 0.0f, 0.0f);
+    ballWheelNode.position = Vector3(3.8f, 0.9f, 0.0f);
+
+    ConstraintWheel2D@ constraintWheel = boxWheelNode.CreateComponent("ConstraintWheel2D");
+    constraintWheel.otherBody = ballWheelNode.GetComponent("RigidBody2D"); // Constrain ball to box
+    constraintWheel.anchor = Vector2(ballWheelNode.position.x, ballWheelNode.position.y);
+    constraintWheel.axis = Vector2(0.0f, 1.0f);
+    constraintWheel.enableMotor = true;
+    constraintWheel.maxMotorTorque = 1.0f;
+    constraintWheel.motorSpeed = 0.0f;
+    constraintWheel.frequencyHz = 4.0f;
+    constraintWheel.dampingRatio = 0.5f;
+    constraintWheel.collideConnected = true; // doesn't work
+}
+
+void CreateFlag(const String&in text, float x, float y) // Used to create Tex3D flags
+{
+    Node@ flagNode = scene_.CreateChild("Flag");
+    flagNode.position = Vector3(x, y, 0.0f);
+    Text3D@ flag3D = flagNode.CreateComponent("Text3D"); // We use Text3D in order to make the text affected by zoom (so that it sticks to 2D)
+    flag3D.text = text;
+    flag3D.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
+}
+
+void CreateInstructions()
+{
+    // Construct new Text object, set string to display and font to use
+    Text@ instructionText = ui.root.CreateChild("Text");
+    instructionText.text = "Use WASD keys and mouse to move, Use PageUp PageDown to zoom.\n Space to toggle debug geometry and joints - F5 to save the scene.";
+    instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
+    instructionText.textAlignment = HA_CENTER; // Center rows in relation to each other
+
+    // Position the text relative to the screen center
+    instructionText.horizontalAlignment = HA_CENTER;
+    instructionText.verticalAlignment = VA_CENTER;
+
+    instructionText.SetPosition(0.0f, ui.root.height / 4);
+}
+
+
+void MoveCamera(float timeStep)
+{
+    if (ui.focusElement !is null) return; // Do not move if the UI has a focused element (the console)
+
+    uint MOVE_SPEED = 4; // Movement speed as world units per second
+
+    // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
+    if (input.keyDown['W']) cameraNode.Translate(Vector3(0.0f, 1.0f, 0.0f) * MOVE_SPEED * timeStep);
+    if (input.keyDown['S']) cameraNode.Translate(Vector3(0.0f, -1.0f, 0.0f) * MOVE_SPEED * timeStep);
+    if (input.keyDown['A']) cameraNode.Translate(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
+    if (input.keyDown['D']) cameraNode.Translate(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
+
+    if (input.keyDown[KEY_PAGEUP]) camera.zoom = camera.zoom * 1.01f; // Zoom In
+    if (input.keyDown[KEY_PAGEDOWN]) camera.zoom = camera.zoom * 0.99f; // Zoom Out
+}
+
+void SubscribeToEvents()
+{
+    SubscribeToEvent("Update", "HandleUpdate");
+    SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
+    SubscribeToEvent("MouseButtonDown", "HandleMouseButtonDown");
+
+    if (touchEnabled)
+        SubscribeToEvent("TouchBegin", "HandleTouchBegin3");
+
+    // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
+    UnsubscribeFromEvent("SceneUpdate");
+}
+
+void HandleUpdate(StringHash eventType, VariantMap& eventData)
+{
+    float timeStep = eventData["TimeStep"].GetFloat();
+    MoveCamera(timeStep); // Move the camera according to frame's time step
+    if (input.keyPress[KEY_SPACE]) drawDebug = !drawDebug; // Toggle debug geometry with space
+    if (input.keyPress[KEY_F5]) // Save scene
+    {
+        File saveFile(fileSystem.programDir + "Data/Scenes/Constraints.xml", FILE_WRITE);
+        scene_.SaveXML(saveFile);
+    }
+}
+
+void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
+{
+    PhysicsWorld2D@ physicsWorld = scene_.GetComponent("PhysicsWorld2D");
+    if (drawDebug) physicsWorld.DrawDebugGeometry();
+}
+
+void HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
+{
+    PhysicsWorld2D@ physicsWorld = scene_.GetComponent("PhysicsWorld2D");
+    RigidBody2D@ rigidBody = physicsWorld.GetRigidBody(input.mousePosition.x, input.mousePosition.y, M_MAX_UNSIGNED ,camera); // Raycast for RigidBody2Ds to pick
+    if (rigidBody !is null)
+    {
+        pickedNode = rigidBody.node;
+        StaticSprite2D@ staticSprite = pickedNode.GetComponent("StaticSprite2D");
+        staticSprite.color = Color(1.0f, 0.0f, 0.0f, 1.0f); // Temporary modify color of the picked sprite
+
+        // Create a ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with the mouse
+        ConstraintMouse2D@ constraintMouse = pickedNode.CreateComponent("ConstraintMouse2D");
+        constraintMouse.target = GetMousePositionXY();
+        constraintMouse.maxForce = 1000 * rigidBody.mass;
+        constraintMouse.collideConnected = true;
+        constraintMouse.otherBody = dummyBody;  // Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
+        constraintMouse.dampingRatio = 0.0f;
+    }
+    SubscribeToEvent("MouseMove", "HandleMouseMove");
+    SubscribeToEvent("MouseButtonUp", "HandleMouseButtonUp");
+}
+
+void HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
+{
+    if (pickedNode !is null)
+    {
+        StaticSprite2D@ staticSprite = pickedNode.GetComponent("StaticSprite2D");
+        staticSprite.color = Color(1.0f, 1.0f, 1.0f, 1.0f); // Restore picked sprite color
+
+        pickedNode.RemoveComponent("ConstraintMouse2D"); // Remove temporary constraint
+        pickedNode = null;
+    }
+    UnsubscribeFromEvent("MouseMove");
+    UnsubscribeFromEvent("MouseButtonUp");
+}
+
+Vector2 GetMousePositionXY()
+{
+    Vector3 screenPoint = Vector3(float(input.mousePosition.x) / graphics.width, float(input.mousePosition.y) / graphics.height, 0.0f);
+    Vector3 worldPoint = camera.ScreenToWorldPoint(screenPoint);
+    return Vector2(worldPoint.x, worldPoint.y);
+}
+
+void HandleMouseMove(StringHash eventType, VariantMap& eventData)
+{
+    if (pickedNode !is null)
+    {
+        ConstraintMouse2D@ constraintMouse = pickedNode.GetComponent("ConstraintMouse2D");
+        constraintMouse.target = GetMousePositionXY();
+    }
+}
+
+void HandleTouchBegin3(StringHash eventType, VariantMap& eventData)
+{
+    PhysicsWorld2D@ physicsWorld = scene_.GetComponent("PhysicsWorld2D");
+    RigidBody2D@ rigidBody = physicsWorld.GetRigidBody(eventData["X"].GetInt(), eventData["Y"].GetInt(), M_MAX_UNSIGNED ,camera); // Raycast for RigidBody2Ds to pick
+    if (rigidBody !is null)
+    {
+        pickedNode = rigidBody.node;
+        StaticSprite2D@ staticSprite = pickedNode.GetComponent("StaticSprite2D");
+        staticSprite.color = Color(1.0f, 0.0f, 0.0f, 1.0f); // Temporary modify color of the picked sprite
+        RigidBody2D@ rigidBody = pickedNode.GetComponent("RigidBody2D");
+
+        // Create a ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with touch
+        ConstraintMouse2D@ constraintMouse = pickedNode.CreateComponent("ConstraintMouse2D");
+        Vector3 pos = camera.ScreenToWorldPoint(Vector3(float(eventData["X"].GetInt()) / graphics.width, float(eventData["Y"].GetInt()) / graphics.height, 0.0f));
+        constraintMouse.target = Vector2(pos.x, pos.y);
+        constraintMouse.maxForce = 1000 * rigidBody.mass;
+        constraintMouse.collideConnected = true;
+        constraintMouse.otherBody = dummyBody;  // Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
+        constraintMouse.dampingRatio = 0;
+    }
+    SubscribeToEvent("TouchMove", "HandleTouchMove3");
+    SubscribeToEvent("TouchEnd", "HandleTouchEnd3");
+}
+
+void HandleTouchMove3(StringHash eventType, VariantMap& eventData)
+{
+    if (pickedNode !is null)
+    {
+        ConstraintMouse2D@ constraintMouse = pickedNode.GetComponent("ConstraintMouse2D");
+        Vector3 pos = camera.ScreenToWorldPoint(Vector3(float(eventData["X"].GetInt()) / graphics.width, float(eventData["Y"].GetInt()) / graphics.height, 0.0f));
+        constraintMouse.target = Vector2(pos.x, pos.y);
+    }
+}
+
+void HandleTouchEnd3(StringHash eventType, VariantMap& eventData)
+{
+    if (pickedNode !is null)
+    {
+        StaticSprite2D@ staticSprite = pickedNode.GetComponent("StaticSprite2D");
+        staticSprite.color = Color(1.0f, 1.0f, 1.0f, 1.0f); // Restore picked sprite color
+
+        pickedNode.RemoveComponent("ConstraintMouse2D"); // Remove temporary constraint
+        pickedNode = null;
+    }
+    UnsubscribeFromEvent("TouchMove");
+    UnsubscribeFromEvent("TouchEnd");
+}
+
+// Create XML patch instructions for screen joystick layout specific to this sample app
+String patchInstructions =
+        "<patch>" +
+        "    <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
+        "    <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" +
+        "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
+        "        <element type=\"Text\">" +
+        "            <attribute name=\"Name\" value=\"KeyBinding\" />" +
+        "            <attribute name=\"Text\" value=\"PAGEUP\" />" +
+        "        </element>" +
+        "    </add>" +
+        "    <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
+        "    <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" +
+        "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
+        "        <element type=\"Text\">" +
+        "            <attribute name=\"Name\" value=\"KeyBinding\" />" +
+        "            <attribute name=\"Text\" value=\"PAGEDOWN\" />" +
+        "        </element>" +
+        "    </add>" +
+        "</patch>";

+ 33 - 0
Source/Samples/32_Urho2DConstraints/CMakeLists.txt

@@ -0,0 +1,33 @@
+#
+# Copyright (c) 2008-2014 the Urho3D project.
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+#
+
+# Define target name
+set (TARGET_NAME 32_Urho2DConstraints)
+
+# Define source files
+define_source_files (EXTRA_H_FILES ${COMMON_SAMPLE_H_FILES})
+
+# Setup target with resource copying
+setup_main_executable ()
+
+# Setup test cases
+add_test (NAME ${TARGET_NAME} COMMAND ${TARGET_NAME} -timeout ${URHO3D_TEST_TIME_OUT})

+ 610 - 0
Source/Samples/32_Urho2DConstraints/Urho2DConstraints.cpp

@@ -0,0 +1,610 @@
+//
+// Copyright (c) 2008-2014 the Urho3D project.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+#include "Camera.h"
+#include "CollisionBox2D.h"
+#include "CollisionCircle2D.h"
+#include "CollisionEdge2D.h"
+#include "CollisionPolygon2D.h"
+#include "ConstraintDistance2D.h"
+#include "ConstraintFriction2D.h"
+#include "ConstraintGear2D.h"
+#include "ConstraintMotor2D.h"
+#include "ConstraintMouse2D.h"
+#include "ConstraintPrismatic2D.h"
+#include "ConstraintPulley2D.h"
+#include "ConstraintRevolute2D.h"
+#include "ConstraintRope2D.h"
+#include "ConstraintWeld2D.h"
+#include "ConstraintWheel2D.h"
+#include "CoreEvents.h"
+#include "DebugNew.h"
+#include "DebugRenderer.h"
+#include "Drawable2D.h"
+#include "Engine.h"
+#include "FileSystem.h"
+#include "Font.h"
+#include "Graphics.h"
+#include "Input.h"
+#include "Octree.h"
+#include "PhysicsWorld2D.h"
+#include "Renderer.h"
+#include "ResourceCache.h"
+#include "RigidBody2D.h"
+#include "Scene.h"
+#include "SceneEvents.h"
+#include "Sprite2D.h"
+#include "StaticSprite2D.h"
+#include "Text.h"
+#include "Text3D.h"
+#include "Urho2DConstraints.h"
+#include "Vector.h"
+#include "Zone.h"
+
+DEFINE_APPLICATION_MAIN(Urho2DConstraints)
+
+Node* pickedNode;
+RigidBody2D* dummyBody;
+
+Urho2DConstraints::Urho2DConstraints(Context* context) :
+    Sample(context)
+{
+}
+
+void Urho2DConstraints::Start()
+{
+    // Execute base class startup
+    Sample::Start();
+
+    // Create the scene content
+    CreateScene();
+
+    // Enable OS cursor
+    GetSubsystem<Input>()->SetMouseVisible(true);
+
+    // Create the UI content
+    CreateInstructions();
+
+    // Hook up to the frame update events
+    SubscribeToEvents();
+}
+
+void Urho2DConstraints::CreateScene()
+{
+    scene_ = new Scene(context_);
+    scene_->CreateComponent<Octree>();
+    scene_->CreateComponent<DebugRenderer>();
+    PhysicsWorld2D* physicsWorld = scene_->CreateComponent<PhysicsWorld2D>(); // Create 2D physics world component
+    physicsWorld->SetDrawJoint(true); // Display the joints (Note that DrawDebugGeometry() must be set to true to acually draw the joints)
+    drawDebug_ = true; // Set DrawDebugGeometry() to true
+
+    // Create camera
+    cameraNode_ = scene_->CreateChild("Camera");
+    // Set camera's position
+    cameraNode_->SetPosition(Vector3(0.0f, 0.0f, 0.0f)); // Note that Z setting is discarded; use camera.zoom instead (see MoveCamera() below for example)
+
+    camera_ = cameraNode_->CreateComponent<Camera>();
+    camera_->SetOrthographic(true);
+
+    Graphics* graphics = GetSubsystem<Graphics>();
+    camera_->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
+    camera_->SetZoom(1.2f);
+
+    // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
+    SharedPtr<Viewport> viewport(new Viewport(context_, scene_, camera_));
+    Renderer* renderer = GetSubsystem<Renderer>();
+    renderer->SetViewport(0, viewport);
+
+    Zone* zone = renderer->GetDefaultZone();
+    zone->SetFogColor(Color(0.1f, 0.1f, 0.1f)); // Set background color for the scene
+
+    // Create 4x3 grid
+    for (unsigned i = 0; i<5; ++i)
+    {
+        Node* edgeNode = scene_->CreateChild("VerticalEdge");
+        RigidBody2D* edgeBody = edgeNode->CreateComponent<RigidBody2D>();
+        if (!dummyBody)
+            dummyBody = edgeBody; // Mark first edge as dummy body (used by mouse pick)
+        CollisionEdge2D* edgeShape = edgeNode->CreateComponent<CollisionEdge2D>();
+        edgeShape->SetVertices(Vector2(i*2.5f -5.0f, -3.0f), Vector2(i*2.5f -5.0f, 3.0f));
+        edgeShape->SetFriction(0.5f); // Set friction
+    }
+
+    for (unsigned j = 0; j<4; ++j)
+    {
+        Node* edgeNode = scene_->CreateChild("HorizontalEdge");
+        RigidBody2D* edgeBody = edgeNode->CreateComponent<RigidBody2D>();
+        CollisionEdge2D* edgeShape = edgeNode->CreateComponent<CollisionEdge2D>();
+        edgeShape->SetVertices(Vector2(-5.0f, j*2.0f -3.0f), Vector2(5.0f, j*2.0f -3.0f));
+        edgeShape->SetFriction(0.5f); // Set friction
+    }
+
+    ResourceCache* cache = GetSubsystem<ResourceCache>();
+
+    // Create a box (will be cloned later)
+    Node* box  = scene_->CreateChild("Box");
+    box->SetPosition(Vector3(0.8f, -2.0f, 0.0f));
+    StaticSprite2D* boxSprite = box->CreateComponent<StaticSprite2D>();
+    boxSprite->SetSprite(cache->GetResource<Sprite2D>("Urho2D/Box.png"));
+    RigidBody2D* boxBody = box->CreateComponent<RigidBody2D>();
+    boxBody->SetBodyType(BT_DYNAMIC);
+    boxBody->SetLinearDamping(0.0f);
+    boxBody->SetAngularDamping(0.0f);
+    CollisionBox2D* shape = box->CreateComponent<CollisionBox2D>(); // Create box shape
+    shape->SetSize(Vector2(0.32, 0.32)); // Set size
+    shape->SetDensity(1.0f); // Set shape density (kilograms per meter squared)
+    shape->SetFriction(0.5f); // Set friction
+    shape->SetRestitution(0.1f); // Set restitution (slight bounce)
+
+    // Create a ball (will be cloned later)
+    Node* ball  = scene_->CreateChild("Ball");
+    ball->SetPosition(Vector3(1.8f, -2.0f, 0.0f));
+    StaticSprite2D* ballSprite = ball->CreateComponent<StaticSprite2D>();
+    ballSprite->SetSprite(cache->GetResource<Sprite2D>("Urho2D/Ball.png"));
+    RigidBody2D* ballBody = ball->CreateComponent<RigidBody2D>();
+    ballBody->SetBodyType(BT_DYNAMIC);
+    ballBody->SetLinearDamping(0.0f);
+    ballBody->SetAngularDamping(0.0f);
+    CollisionCircle2D* ballShape = ball->CreateComponent<CollisionCircle2D>(); // Create circle shape
+    ballShape->SetRadius(0.16f); // Set radius
+    ballShape->SetDensity(1.0f); // Set shape density (kilograms per meter squared)
+    ballShape->SetFriction(0.5f); // Set friction
+    ballShape->SetRestitution(0.6f); // Set restitution: make it bounce
+
+    // Create a polygon
+    Node* polygon = scene_->CreateChild("Polygon");
+    polygon->SetPosition(Vector3(1.6f, -2.0f, 0.0f));
+    polygon->SetScale(0.7f);
+    StaticSprite2D* polygonSprite = polygon->CreateComponent<StaticSprite2D>();
+    polygonSprite->SetSprite(cache->GetResource<Sprite2D>("Urho2D/Aster.png"));
+    RigidBody2D* polygonBody = polygon->CreateComponent<RigidBody2D>();
+    polygonBody->SetBodyType(BT_DYNAMIC);
+    CollisionPolygon2D* polygonShape = polygon->CreateComponent<CollisionPolygon2D>();
+    // TODO: create from PODVector<Vector2> using SetVertices()
+    polygonShape->SetVertexCount(6); // Set number of vertices (mandatory when using SetVertex())
+    polygonShape->SetVertex(0, Vector2(-0.8f, -0.3f));
+    polygonShape->SetVertex(1, Vector2(0.5f, -0.8f));
+    polygonShape->SetVertex(2, Vector2(0.8f, -0.3f));
+    polygonShape->SetVertex(3, Vector2(0.8f, 0.5f));
+    polygonShape->SetVertex(4, Vector2(0.5f, 0.9f));
+    polygonShape->SetVertex(5, Vector2(-0.5f, 0.7f));
+    polygonShape->SetDensity(1.0f); // Set shape density (kilograms per meter squared)
+    polygonShape->SetFriction(0.3f); // Set friction
+    polygonShape->SetRestitution(0.0f); // Set restitution (no bounce)
+
+    // Create a ConstraintDistance2D
+    CreateFlag("ConstraintDistance2D", -4.97f, 3.0f); // Display Text3D flag
+    Node* boxDistanceNode = box->Clone();
+    Node* ballDistanceNode = ball->Clone();
+    RigidBody2D* ballDistanceBody = ballDistanceNode->GetComponent<RigidBody2D>();
+    boxDistanceNode->SetPosition(Vector3(-4.5f, 2.0f, 0.0f));
+    ballDistanceNode->SetPosition(Vector3(-3.0f, 2.0f, 0.0f));
+
+    ConstraintDistance2D* constraintDistance = boxDistanceNode->CreateComponent<ConstraintDistance2D>(); // Apply ConstraintDistance2D to box
+    constraintDistance->SetOtherBody(ballDistanceBody); // Constrain ball to box
+    constraintDistance->SetOwnerBodyAnchor(Vector2(boxDistanceNode->GetPosition().x_, boxDistanceNode->GetPosition().y_));
+    constraintDistance->SetOtherBodyAnchor(Vector2(ballDistanceNode->GetPosition().x_, ballDistanceNode->GetPosition().y_));
+    // Make the constraint soft (comment to make it rigid, which is its basic behavior)
+    constraintDistance->SetFrequencyHz(4.0f);
+    constraintDistance->SetDampingRatio(0.5f);
+
+    // Create a ConstraintFriction2D ********** Not functional. From Box2d samples it seems that 2 anchors are required, Urho2D only provides 1, needs investigation ***********
+    CreateFlag("ConstraintFriction2D", 0.03f, 1.0f); // Display Text3D flag
+    Node* boxFrictionNode = box->Clone();
+    Node* ballFrictionNode = ball->Clone();
+    boxFrictionNode->SetPosition(Vector3(0.5f, 0.0f, 0.0f));
+    ballFrictionNode->SetPosition(Vector3(1.5f, 0.0f, 0.0f));
+
+    ConstraintFriction2D* constraintFriction = boxFrictionNode->CreateComponent<ConstraintFriction2D>(); // Apply ConstraintDistance2D to box
+    constraintFriction->SetOtherBody(ballFrictionNode->GetComponent<RigidBody2D>()); // Constraint ball to box
+    //constraintFriction->SetOwnerBodyAnchor(Vector2(boxNode->GetPosition().x_, boxNode->GetPosition().y_);
+    //constraintFriction->SetOtherBodyAnchor(Vector2(ballNode->GetPosition().x_, ballNode->GetPosition().y_);
+    //constraintFriction->SetMaxForce(10.0f); // ballBody.mass * gravity
+    //constraintDistance->SetMaxTorque(10.0f); // ballBody.mass * radius * gravity
+
+    // Create a ConstraintGear2D
+    CreateFlag("ConstraintGear2D", -4.97f, -1.0f); // Display Text3D flag
+    Node* baseNode = box->Clone();
+    RigidBody2D* tempBody = baseNode->GetComponent<RigidBody2D>(); // Get body to make it static
+    tempBody->SetBodyType(BT_STATIC);
+    baseNode->SetPosition(Vector3(-3.7f, -2.5f, 0.0f));
+    Node* ball1Node = ball->Clone();
+    ball1Node->SetPosition(Vector3(-4.5f, -2.0f, 0.0f));
+    RigidBody2D* ball1Body = ball1Node->GetComponent<RigidBody2D>();
+    Node* ball2Node = ball->Clone();
+    ball2Node->SetPosition(Vector3(-3.0f, -2.0f, 0.0f));
+    RigidBody2D* ball2Body = ball2Node->GetComponent<RigidBody2D>();
+
+    ConstraintRevolute2D* gear1 = baseNode->CreateComponent<ConstraintRevolute2D>(); // Apply constraint to baseBox
+    gear1->SetOtherBody(ball1Body); // Constrain ball1 to baseBox
+    gear1->SetAnchor(Vector2(ball1Node->GetPosition().x_, ball1Node->GetPosition().y_));
+    ConstraintRevolute2D* gear2 = baseNode->CreateComponent<ConstraintRevolute2D>(); // Apply constraint to baseBox
+    gear2->SetOtherBody(ball2Body); // Constrain ball2 to baseBox
+    gear2->SetAnchor(Vector2(ball2Node->GetPosition().x_, ball2Node->GetPosition().y_));
+
+    ConstraintGear2D* constraintGear = ball1Node->CreateComponent<ConstraintGear2D>(); // Apply constraint to ball1
+    constraintGear->SetOtherBody(ball2Body); // Constrain ball2 to ball1
+    constraintGear->SetOwnerConstraint(gear1);
+    constraintGear->SetOtherConstraint(gear2);
+    constraintGear->SetRatio(1.0f);
+
+    ball1Body->ApplyAngularImpulse(0.015f, true); // Animate
+
+    // Create a vehicle from a compound of 2 ConstraintWheel2Ds
+    CreateFlag("ConstraintWheel2Ds compound", -2.45f, -1.0f); // Display Text3D flag
+    Node* car = box->Clone();
+    car->SetScale(Vector3(4.0f, 1.0f, 0.0f));
+    car->SetPosition(Vector3(-1.2f, -2.3f, 0.0f));
+    StaticSprite2D* tempSprite = car->GetComponent<StaticSprite2D>(); // Get car Sprite in order to draw it on top
+    tempSprite->SetOrderInLayer(0); // Draw car on top of the wheels (set to -1 to draw below)
+    Node* ball1WheelNode = ball->Clone();
+    ball1WheelNode->SetPosition(Vector3(-1.6f, -2.5f, 0.0f));
+    Node* ball2WheelNode = ball->Clone();
+    ball2WheelNode->SetPosition(Vector3(-0.8f, -2.5f, 0.0f));
+
+    ConstraintWheel2D* wheel1 = car->CreateComponent<ConstraintWheel2D>();
+    wheel1->SetOtherBody(ball1WheelNode->GetComponent<RigidBody2D>());
+    wheel1->SetAnchor(Vector2(ball1WheelNode->GetPosition().x_, ball1WheelNode->GetPosition().y_));
+    wheel1->SetAxis(Vector2(0.0f, 1.0f));
+    wheel1->SetMaxMotorTorque(20.0f);
+    wheel1->SetFrequencyHz(4.0f);
+    wheel1->SetDampingRatio(0.4f);
+
+    ConstraintWheel2D* wheel2 = car->CreateComponent<ConstraintWheel2D>();
+    wheel2->SetOtherBody(ball2WheelNode->GetComponent<RigidBody2D>());
+    wheel2->SetAnchor(Vector2(ball2WheelNode->GetPosition().x_, ball2WheelNode->GetPosition().y_));
+    wheel2->SetAxis(Vector2(0.0f, 1.0f));
+    wheel2->SetMaxMotorTorque(10.0f);
+    wheel2->SetFrequencyHz(4.0f);
+    wheel2->SetDampingRatio(0.4f);
+
+    // ConstraintMotor2D
+    CreateFlag("ConstraintMotor2D", 2.53f, -1.0f); // Display Text3D flag
+    Node* boxMotorNode = box->Clone();
+    tempBody = boxMotorNode->GetComponent<RigidBody2D>(); // Get body to make it static
+    tempBody->SetBodyType(BT_STATIC);
+    Node* ballMotorNode = ball->Clone();
+    boxMotorNode->SetPosition(Vector3(3.8f, -2.1f, 0.0f));
+    ballMotorNode->SetPosition(Vector3(3.8f, -1.5f, 0.0f));
+
+    ConstraintMotor2D* constraintMotor = boxMotorNode->CreateComponent<ConstraintMotor2D>();
+    constraintMotor->SetOtherBody(ballMotorNode->GetComponent<RigidBody2D>()); // Constrain ball to box
+    constraintMotor->SetLinearOffset(Vector2(0.0f, 0.8f)); // Set ballNode position relative to boxNode position = (0,0)
+    constraintMotor->SetAngularOffset(0.1f);
+    constraintMotor->SetMaxForce(5.0f);
+    constraintMotor->SetMaxTorque(10.0f);
+    constraintMotor->SetCorrectionFactor(1.0f);
+    constraintMotor->SetCollideConnected(true); // doesn't work
+
+    // ConstraintMouse2D is demonstrated in HandleMouseButtonDown() function. It is used to "grasp" the sprites with the mouse.
+    CreateFlag("ConstraintMouse2D", 0.03f, -1.0f); // Display Text3D flag
+
+    // Create a ConstraintPrismatic2D
+    CreateFlag("ConstraintPrismatic2D", 2.53f, 3.0f); // Display Text3D flag
+    Node* boxPrismaticNode = box->Clone();
+    tempBody = boxPrismaticNode->GetComponent<RigidBody2D>(); // Get body to make it static
+    tempBody->SetBodyType(BT_STATIC);
+    Node* ballPrismaticNode = ball->Clone();
+    boxPrismaticNode->SetPosition(Vector3(3.3f, 2.5f, 0.0f));
+    ballPrismaticNode->SetPosition(Vector3(4.3f, 2.0f, 0.0f));
+
+    ConstraintPrismatic2D* constraintPrismatic = boxPrismaticNode->CreateComponent<ConstraintPrismatic2D>();
+    constraintPrismatic->SetOtherBody(ballPrismaticNode->GetComponent<RigidBody2D>()); // Constrain ball to box
+    constraintPrismatic->SetAxis(Vector2(1.0f, 1.0f)); // Slide from [0,0] to [1,1]
+    constraintPrismatic->SetAnchor(Vector2(4.0f, 2.0f));
+    constraintPrismatic->SetLowerTranslation(-1.0f);
+    constraintPrismatic->SetUpperTranslation(0.5f);
+    constraintPrismatic->SetEnableLimit(true);
+    constraintPrismatic->SetMaxMotorForce(1.0f);
+    constraintPrismatic->SetMotorSpeed(0.0f);
+
+    // ConstraintPulley2D
+    CreateFlag("ConstraintPulley2D", 0.03f, 3.0f); // Display Text3D flag
+    Node* boxPulleyNode = box->Clone();
+    Node* ballPulleyNode = ball->Clone();
+    boxPulleyNode->SetPosition(Vector3(0.5f, 2.0f, 0.0f));
+    ballPulleyNode->SetPosition(Vector3(2.0f, 2.0f, 0.0f));
+
+    ConstraintPulley2D* constraintPulley = boxPulleyNode->CreateComponent<ConstraintPulley2D>(); // Apply constraint to box
+    constraintPulley->SetOtherBody(ballPulleyNode->GetComponent<RigidBody2D>()); // Constrain ball to box
+    constraintPulley->SetOwnerBodyAnchor(Vector2(boxPulleyNode->GetPosition().x_, boxPulleyNode->GetPosition().y_));
+    constraintPulley->SetOtherBodyAnchor(Vector2(ballPulleyNode->GetPosition().x_, ballPulleyNode->GetPosition().y_));
+    constraintPulley->SetOwnerBodyGroundAnchor(Vector2(boxPulleyNode->GetPosition().x_, boxPulleyNode->GetPosition().y_ + 1));
+    constraintPulley->SetOtherBodyGroundAnchor(Vector2(ballPulleyNode->GetPosition().x_, ballPulleyNode->GetPosition().y_ + 1));
+    constraintPulley->SetRatio(1.0); // Weight ratio between ownerBody and otherBody
+
+    // Create a ConstraintRevolute2D
+    CreateFlag("ConstraintRevolute2D", -2.45f, 3.0f); // Display Text3D flag
+    Node* boxRevoluteNode = box->Clone();
+    tempBody = boxRevoluteNode->GetComponent<RigidBody2D>(); // Get body to make it static
+    tempBody->SetBodyType(BT_STATIC);
+    Node* ballRevoluteNode = ball->Clone();
+    boxRevoluteNode->SetPosition(Vector3(-2.0f, 1.5f, 0.0f));
+    ballRevoluteNode->SetPosition(Vector3(-1.0f, 2.0f, 0.0f));
+
+    ConstraintRevolute2D* constraintRevolute = boxRevoluteNode->CreateComponent<ConstraintRevolute2D>(); // Apply constraint to box
+    constraintRevolute->SetOtherBody(ballRevoluteNode->GetComponent<RigidBody2D>()); // Constrain ball to box
+    constraintRevolute->SetAnchor(Vector2(-1.0f, 1.5f));
+    constraintRevolute->SetLowerAngle(-1.0f); // In radians
+    constraintRevolute->SetUpperAngle(0.5f); // In radians
+    constraintRevolute->SetEnableLimit(true);
+    constraintRevolute->SetMaxMotorTorque(10.0f);
+    constraintRevolute->SetMotorSpeed(0.0f);
+    constraintRevolute->SetEnableMotor(true);
+
+    // Create a ConstraintRope2D
+    CreateFlag("ConstraintRope2D", -4.97f, 1.0f); // Display Text3D flag
+    Node* boxRopeNode = box->Clone();
+    tempBody = boxRopeNode->GetComponent<RigidBody2D>();
+    tempBody->SetBodyType(BT_STATIC);
+    Node* ballRopeNode = ball->Clone();
+    boxRopeNode->SetPosition(Vector3(-3.7f, 0.7f, 0.0f));
+    ballRopeNode->SetPosition(Vector3(-4.5f, 0.0f, 0.0f));
+
+    ConstraintRope2D* constraintRope = boxRopeNode->CreateComponent<ConstraintRope2D>();
+    constraintRope->SetOtherBody(ballRopeNode->GetComponent<RigidBody2D>()); // Constrain ball to box
+    constraintRope->SetOwnerBodyAnchor(Vector2(0.0f, -0.5f)); // Offset from box (OwnerBody) : the rope is rigid from OwnerBody center to this ownerBodyAnchor
+    constraintRope->SetMaxLength(0.9f); // Rope length
+    constraintRope->SetCollideConnected(true);
+
+    // Create a ConstraintWeld2D
+    CreateFlag("ConstraintWeld2D", -2.45f, 1.0f); // Display Text3D flag
+    Node* boxWeldNode = box->Clone();
+    Node* ballWeldNode = ball->Clone();
+    boxWeldNode->SetPosition(Vector3(-0.5f, 0.0f, 0.0f));
+    ballWeldNode->SetPosition(Vector3(-2.0f, 0.0f, 0.0f));
+
+    ConstraintWeld2D* constraintWeld = boxWeldNode->CreateComponent<ConstraintWeld2D>();
+    constraintWeld->SetOtherBody(ballWeldNode->GetComponent<RigidBody2D>()); // Constrain ball to box
+    constraintWeld->SetAnchor(Vector2(boxWeldNode->GetPosition().x_, boxWeldNode->GetPosition().y_));
+    constraintWeld->SetFrequencyHz(4.0f);
+    constraintWeld->SetDampingRatio(0.5f);
+
+    // Create a ConstraintWheel2D
+    CreateFlag("ConstraintWheel2D",  2.53f, 1.0f); // Display Text3D flag
+    Node* boxWheelNode = box->Clone();
+    Node* ballWheelNode = ball->Clone();
+    boxWheelNode->SetPosition(Vector3(3.8f, 0.0f, 0.0f));
+    ballWheelNode->SetPosition(Vector3(3.8f, 0.9f, 0.0f));
+
+    ConstraintWheel2D* constraintWheel = boxWheelNode->CreateComponent<ConstraintWheel2D>();
+    constraintWheel->SetOtherBody(ballWheelNode->GetComponent<RigidBody2D>()); // Constrain ball to box
+    constraintWheel->SetAnchor(Vector2(ballWheelNode->GetPosition().x_, ballWheelNode->GetPosition().y_));
+    constraintWheel->SetAxis(Vector2(0.0f, 1.0f));
+    constraintWheel->SetEnableMotor(true);
+    constraintWheel->SetMaxMotorTorque(1.0f);
+    constraintWheel->SetMotorSpeed(0.0f);
+    constraintWheel->SetFrequencyHz(4.0f);
+    constraintWheel->SetDampingRatio(0.5f);
+    constraintWheel->SetCollideConnected(true); // doesn't work
+}
+
+void Urho2DConstraints::CreateFlag(const String& text, float x, float y) // Used to create Tex3D flags
+{
+    Node* flagNode = scene_->CreateChild("Flag");
+    flagNode->SetPosition(Vector3(x, y, 0.0f));
+    Text3D* flag3D = flagNode->CreateComponent<Text3D>(); // We use Text3D in order to make the text affected by zoom (so that it sticks to 2D)
+    flag3D->SetText(text);
+    ResourceCache* cache = GetSubsystem<ResourceCache>();
+    flag3D->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
+}
+
+void Urho2DConstraints::CreateInstructions()
+{
+    ResourceCache* cache = GetSubsystem<ResourceCache>();
+    UI* ui = GetSubsystem<UI>();
+
+    // Construct new Text object, set string to display and font to use
+    Text* instructionText = ui->GetRoot()->CreateChild<Text>();
+    instructionText->SetText("Use WASD keys and mouse to move, Use PageUp PageDown to zoom.\n Space to toggle debug geometry and joints - F5 to save the scene.");
+    instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
+    instructionText->SetTextAlignment(HA_CENTER); // Center rows in relation to each other
+
+    // Position the text relative to the screen center
+    instructionText->SetHorizontalAlignment(HA_CENTER);
+    instructionText->SetVerticalAlignment(VA_CENTER);
+    instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
+}
+
+void Urho2DConstraints::MoveCamera(float timeStep)
+{
+    // Do not move if the UI has a focused element (the console)
+    if (GetSubsystem<UI>()->GetFocusElement())
+        return;
+
+    Input* input = GetSubsystem<Input>();
+
+    // Movement speed as world units per second
+    const float MOVE_SPEED = 4.0f;
+
+    // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
+    if (input->GetKeyDown('W'))
+        cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
+    if (input->GetKeyDown('S'))
+        cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
+    if (input->GetKeyDown('A'))
+        cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
+    if (input->GetKeyDown('D'))
+        cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
+
+    if (input->GetKeyDown(KEY_PAGEUP))
+        camera_->SetZoom(camera_->GetZoom() * 1.01f);
+
+    if (input->GetKeyDown(KEY_PAGEDOWN))
+        camera_->SetZoom(camera_->GetZoom() * 0.99f);
+}
+
+void Urho2DConstraints::SubscribeToEvents()
+{
+    // Subscribe HandleUpdate() function for processing update events
+    SubscribeToEvent(E_UPDATE, HANDLER(Urho2DConstraints, HandleUpdate));
+
+    // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request debug geometry
+    SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(Urho2DConstraints, HandlePostRenderUpdate));
+
+    // Subscribe to mouse click
+    SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(Urho2DConstraints, HandleMouseButtonDown));
+
+    // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
+    UnsubscribeFromEvent(E_SCENEUPDATE);
+
+    if (touchEnabled_)
+        SubscribeToEvent(E_TOUCHBEGIN, HANDLER(Urho2DConstraints, HandleTouchBegin3));
+}
+
+void Urho2DConstraints::HandleUpdate(StringHash eventType, VariantMap& eventData)
+{
+    using namespace Update;
+
+    // Take the frame time step, which is stored as a float
+    float timeStep = eventData[P_TIMESTEP].GetFloat();
+
+    // Move the camera, scale movement with time step
+    MoveCamera(timeStep);
+
+    Input* input = GetSubsystem<Input>();
+
+    // Toggle physics debug geometry with space
+    if (input->GetKeyPress(KEY_SPACE))
+        drawDebug_ = !drawDebug_;
+
+    // Save scene
+    if (input->GetKeyPress(KEY_F5))
+    {
+        File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/Constraints.xml", FILE_WRITE);
+        scene_->SaveXML(saveFile);
+    }
+}
+
+void Urho2DConstraints::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
+{
+    PhysicsWorld2D* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
+    if (drawDebug_) physicsWorld->DrawDebugGeometry();
+}
+
+void Urho2DConstraints::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
+{
+    Input* input = GetSubsystem<Input>();
+    PhysicsWorld2D* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
+    RigidBody2D* rigidBody = physicsWorld->GetRigidBody(input->GetMousePosition().x_, input->GetMousePosition().y_, M_MAX_UNSIGNED, camera_); // Raycast for RigidBody2Ds to pick
+    if (rigidBody)
+    {
+        pickedNode = rigidBody->GetNode();
+        //log.Info(pickedNode.name);
+        StaticSprite2D* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
+        staticSprite->SetColor(Color(1.0f, 0.0f, 0.0f, 1.0f)); // Temporary modify color of the picked sprite
+
+        // Create a ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with the mouse
+        ConstraintMouse2D* constraintMouse = pickedNode->CreateComponent<ConstraintMouse2D>();
+        constraintMouse->SetTarget(GetMousePositionXY());
+        constraintMouse->SetMaxForce(1000 * rigidBody->GetMass());
+        constraintMouse->SetCollideConnected(true);
+        constraintMouse->SetOtherBody(dummyBody);  // Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
+        constraintMouse->SetDampingRatio(0.0f);
+    }
+    SubscribeToEvent(E_MOUSEMOVE, HANDLER(Urho2DConstraints, HandleMouseMove));
+    SubscribeToEvent(E_MOUSEBUTTONUP, HANDLER(Urho2DConstraints, HandleMouseButtonUp));
+}
+
+void Urho2DConstraints::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
+{
+    if (pickedNode)
+    {
+        StaticSprite2D* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
+        staticSprite->SetColor(Color(1.0f, 1.0f, 1.0f, 1.0f)); // Restore picked sprite color
+
+        pickedNode->RemoveComponent<ConstraintMouse2D>(); // Remove temporary constraint
+        pickedNode = NULL;
+    }
+    UnsubscribeFromEvent(E_MOUSEMOVE);
+    UnsubscribeFromEvent(E_MOUSEBUTTONUP);
+}
+
+Vector2 Urho2DConstraints::GetMousePositionXY()
+{
+    Input* input = GetSubsystem<Input>();
+    Graphics* graphics = GetSubsystem<Graphics>();
+    Vector3 screenPoint = Vector3((float)input->GetMousePosition().x_ / graphics->GetWidth(), (float)input->GetMousePosition().y_ / graphics->GetHeight(), 0.0f);
+    Vector3 worldPoint = camera_->ScreenToWorldPoint(screenPoint);
+    return Vector2(worldPoint.x_, worldPoint.y_);
+}
+
+void Urho2DConstraints::HandleMouseMove(StringHash eventType, VariantMap& eventData)
+{
+    if (pickedNode)
+    {
+        ConstraintMouse2D* constraintMouse = pickedNode->GetComponent<ConstraintMouse2D>();
+        constraintMouse->SetTarget(GetMousePositionXY());
+    }
+}
+
+void Urho2DConstraints::HandleTouchBegin3(StringHash eventType, VariantMap& eventData)
+{
+    Graphics* graphics = GetSubsystem<Graphics>();
+    PhysicsWorld2D* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
+    using namespace TouchBegin;
+    RigidBody2D* rigidBody = physicsWorld->GetRigidBody(Vector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt())); // Raycast for RigidBody2Ds to pick
+    if (rigidBody)
+    {
+        pickedNode = rigidBody->GetNode();
+        StaticSprite2D* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
+        staticSprite->SetColor(Color(1.0f, 0.0f, 0.0f, 1.0f)); // Temporary modify color of the picked sprite
+        RigidBody2D* rigidBody = pickedNode->GetComponent<RigidBody2D>();
+
+        // Create a ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with touch
+        ConstraintMouse2D* constraintMouse = pickedNode->CreateComponent<ConstraintMouse2D>();
+        Vector3 pos = camera_->ScreenToWorldPoint(Vector3((float)eventData[P_X].GetInt() / graphics->GetWidth(), (float)eventData[P_Y].GetInt() / graphics->GetHeight(), 0.0f));
+        constraintMouse->SetTarget(Vector2(pos.x_, pos.y_));
+        constraintMouse->SetMaxForce(1000 * rigidBody->GetMass());
+        constraintMouse->SetCollideConnected(true);
+        constraintMouse->SetOtherBody(dummyBody);  // Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
+        constraintMouse->SetDampingRatio(0);
+    }
+    SubscribeToEvent(E_TOUCHMOVE, HANDLER(Urho2DConstraints, HandleTouchMove3));
+    SubscribeToEvent(E_TOUCHEND, HANDLER(Urho2DConstraints, HandleTouchEnd3));
+}
+
+void Urho2DConstraints::HandleTouchMove3(StringHash eventType, VariantMap& eventData)
+{
+    if (pickedNode)
+    {
+        Graphics* graphics = GetSubsystem<Graphics>();
+        ConstraintMouse2D* constraintMouse = pickedNode->GetComponent<ConstraintMouse2D>();
+        using namespace TouchMove;
+        Vector3 pos = camera_->ScreenToWorldPoint(Vector3(float(eventData[P_X].GetInt()) / graphics->GetWidth(), float(eventData[P_Y].GetInt()) / graphics->GetHeight(), 0.0f));
+        constraintMouse->SetTarget(Vector2(pos.x_, pos.y_));
+    }
+}
+
+void Urho2DConstraints::HandleTouchEnd3(StringHash eventType, VariantMap& eventData)
+{
+    if (pickedNode)
+    {
+        StaticSprite2D* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
+        staticSprite->SetColor(Color(1.0f, 1.0f, 1.0f, 1.0f)); // Restore picked sprite color
+
+        pickedNode->RemoveComponent<ConstraintMouse2D>(); // Remove temporary constraint
+        pickedNode = NULL;
+    }
+    UnsubscribeFromEvent(E_TOUCHMOVE);
+    UnsubscribeFromEvent(E_TOUCHEND);
+}

+ 120 - 0
Source/Samples/32_Urho2DConstraints/Urho2DConstraints.h

@@ -0,0 +1,120 @@
+//
+// Copyright (c) 2008-2014 the Urho3D project.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+#pragma once
+
+#include "Sample.h"
+
+namespace Urho3D
+{
+    class Node;
+    class Scene;
+    class ConstraintDistance2D;
+    class ConstraintFriction2D;
+    class ConstraintGear2D;
+    class ConstraintMotor2D;
+    class ConstraintMouse2D;
+    class ConstraintPrismatic2D;
+    class ConstraintPulley2D;
+    class ConstraintRevolute2D;
+    class ConstraintRope2D;
+    class ConstraintWeld2D;
+    class ConstraintWheel2D;
+}
+
+/// Urho2D constraints sample.
+/// This sample is designed to help understanding and chosing the right constraint.
+/// This sample demonstrates:
+///     - Creating physics constraints
+///     - Creating Edge and Polygon Shapes from vertices
+///     - Displaying physics debug geometry and constraints' joints
+///     - Using SetOrderInLayer to alter the way sprites are drawn in relation to each other
+///     - Using Text3D to display some text affected by zoom
+///     - Setting the background color for the scene
+class Urho2DConstraints : public Sample
+{
+    OBJECT(Urho2DConstraints);
+
+public:
+    /// Construct.
+    Urho2DConstraints(Context* context);
+
+    /// Setup after engine initialization and before running the main loop.
+    virtual void Start();
+
+protected:
+    /// Return XML patch instructions for screen joystick layout for a specific sample app, if any.
+    virtual String GetScreenJoystickPatchString() const { return
+        "<patch>"
+        "    <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />"
+        "    <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>"
+        "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">"
+        "        <element type=\"Text\">"
+        "            <attribute name=\"Name\" value=\"KeyBinding\" />"
+        "            <attribute name=\"Text\" value=\"PAGEUP\" />"
+        "        </element>"
+        "    </add>"
+        "    <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />"
+        "    <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>"
+        "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">"
+        "        <element type=\"Text\">"
+        "            <attribute name=\"Name\" value=\"KeyBinding\" />"
+        "            <attribute name=\"Text\" value=\"PAGEDOWN\" />"
+        "        </element>"
+        "    </add>"
+        "</patch>";
+    }
+
+private:
+    /// Construct the scene content.
+    void CreateScene();
+    /// Construct an instruction text to the UI.
+    void CreateInstructions();
+    /// Create Tex3D flag.
+    void CreateFlag(const String& text, float x, float y);
+    /// Read input and moves the camera.
+    void MoveCamera(float timeStep);
+    /// Subscribe to application-wide logic update events.
+    void SubscribeToEvents();
+    /// Handle the logic update event.
+    void HandleUpdate(StringHash eventType, VariantMap& eventData);
+    /// Handle the post render update event during which we request debug geometry.
+    void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData);
+    /// Handle the mouse click event.
+    void HandleMouseButtonDown(StringHash eventType, VariantMap& eventData);
+    /// Handle the mouse button up event.
+    void HandleMouseButtonUp(StringHash eventType, VariantMap& eventData);
+    /// Handle the mouse move event.
+    void HandleMouseMove(StringHash eventType, VariantMap& eventData);
+    /// Handle the touch begin event.
+    void HandleTouchBegin3(StringHash eventType, VariantMap& eventData);
+    /// Handle the touch move event.
+    void HandleTouchMove3(StringHash eventType, VariantMap& eventData);
+    /// Handle the touch end event.
+    void HandleTouchEnd3(StringHash eventType, VariantMap& eventData);
+    /// Get mouse position in 2D world coordinates.
+    Vector2 GetMousePositionXY();
+    /// Flag for drawing debug geometry.
+    bool drawDebug_;
+    /// Camera object.
+    Camera* camera_;
+};

+ 2 - 1
Source/Samples/CMakeLists.txt

@@ -68,4 +68,5 @@ add_subdirectory (27_Urho2DPhysics)
 add_subdirectory (28_Urho2DPhysicsRope)
 add_subdirectory (28_Urho2DPhysicsRope)
 add_subdirectory (29_SoundSynthesis)
 add_subdirectory (29_SoundSynthesis)
 add_subdirectory (30_LightAnimation)
 add_subdirectory (30_LightAnimation)
-add_subdirectory (31_MaterialAnimation)
+#add_subdirectory (31_MaterialAnimation)
+add_subdirectory (32_Urho2DConstraints)