Guest User

Untitled

a guest
Apr 16th, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 10.40 KB | None | 0 0
  1. -- Urho2D physics Constraints sample.
  2. -- This sample is designed to help understanding and chosing the right constraint.
  3. -- This sample demonstrates:
  4. --      - Creating physics constraints
  5. --      - Creating Edge and Polygon Shapes from vertices
  6. --      - Displaying physics debug geometry and constraints' joints
  7. --      - Using SetOrderInLayer to alter the way sprites are drawn in relation to each other
  8. --      - Using Text3D to display some text affected by zoom
  9. --      - Setting the background color for the scene
  10.  
  11. require "LuaScripts/Utilities/Sample"
  12.  
  13. local camera = nil
  14.  
  15. function Start()
  16.     SampleStart()
  17.     CreateScene()
  18.     input.mouseVisible = true -- Show mouse cursor
  19.     CreateInstructions()
  20.     -- Set the mouse mode to use in the sample
  21.     SampleInitMouseMode(MM_FREE)
  22.     SubscribeToEvents()
  23.     print(PIXEL_SIZE)
  24. end
  25.  
  26. function CreateLetterSprite(x,y,z,c,color,size)
  27.     local node = scene_:CreateChild("Background")
  28.     local t=node:CreateComponent("Text3D")
  29.     t.text=c
  30.     t.font=cache:GetResource("Font", "Fonts/BlueHighway.ttf")
  31.     t.fontSize=size
  32.     t.textEffect=TE_STROKE
  33.     t.color=color
  34.     t.horizontalAlignment=HA_CENTER
  35.     t.verticalAlignment=VA_CENTER
  36.     t.effectColor=Color(0,0,0)
  37.     node.position=Vector3(x,y,z)
  38.     return node
  39. end
  40.  
  41. function CreateScene()
  42.     scene_ = Scene()
  43.     scene_:CreateComponent("Octree")
  44.     scene_:CreateComponent("DebugRenderer")
  45.  
  46.     -- Create camera
  47.     cameraNode = scene_:CreateChild("Camera")
  48.     cameraNode.position = Vector3(0, 0, 0) -- Note that Z setting is discarded; use camera.zoom instead (see MoveCamera() below for example)
  49.     camera = cameraNode:CreateComponent("Camera")
  50.     camera.orthographic = true
  51.     camera.orthoSize = graphics.height * 0.01
  52.     camera.zoom = 1 -- Set zoom according to user's resolution to ensure full visibility (initial zoom (1.2) is set for full visibility at 1280x800 resolution)
  53.     renderer:SetViewport(0, Viewport:new(scene_, camera))
  54.     renderer.defaultZone.fogColor = Color(0.1, 0.1, 0.1) -- Set background color for the scene
  55.  
  56.     local x,y
  57.     for x=0,10,1 do
  58.         for y=0,10,1 do
  59.             local n=CreateLetterSprite(x*0.8,y*0.8,1, '#', Color(0.5,0.5,0.5), 100)
  60.         end
  61.     end
  62.  
  63.     dude=CreateLetterSprite(5*0.5, 5*0.8, 0.5, '@', Color(0.5,0.5,1), 100)
  64. end
  65.  
  66.  
  67. function CreateInstructions()
  68.     -- Construct new Text object, set string to display and font to use
  69.     local instructionText = ui.root:CreateChild("Text")
  70.     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.")
  71.     instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  72.     instructionText.textAlignment = HA_CENTER -- Center rows in relation to each other
  73.  
  74.     -- Position the text relative to the screen center
  75.     instructionText.horizontalAlignment = HA_CENTER
  76.     instructionText.verticalAlignment = VA_CENTER
  77.  
  78.     instructionText:SetPosition(0, ui.root.height / 4)
  79. end
  80.  
  81. function MoveCamera(timeStep)
  82.     if ui.focusElement ~= nil then return end -- Do not move if the UI has a focused element (the console)
  83.  
  84.     local MOVE_SPEED = 4 -- Movement speed as world units per second
  85.  
  86.     -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  87.     if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0, 1, 0) * MOVE_SPEED * timeStep) end
  88.     if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0, -1, 0) * MOVE_SPEED * timeStep) end
  89.     if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1, 0, 0) * MOVE_SPEED * timeStep) end
  90.     if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1, 0, 0) * MOVE_SPEED * timeStep) end
  91.  
  92.     if input:GetKeyDown(KEY_PAGEUP) then camera.zoom = camera.zoom * 1.01 end -- Zoom In
  93.     if input:GetKeyDown(KEY_PAGEDOWN) then camera.zoom = camera.zoom * 0.99 end -- Zoom Out
  94. end
  95.  
  96. function SubscribeToEvents()
  97.     SubscribeToEvent("Update", "HandleUpdate")
  98.     SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  99.     SubscribeToEvent("MouseButtonDown", "HandleMouseButtonDown")
  100.     if touchEnabled then SubscribeToEvent("TouchBegin", "HandleTouchBegin3") end
  101.     -- Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  102.     UnsubscribeFromEvent("SceneUpdate")
  103. end
  104.  
  105. function HandleUpdate(eventType, eventData)
  106.     local timestep = eventData["TimeStep"]:GetFloat()
  107.     MoveCamera(timestep) -- Move the camera according to frame's time step
  108.     if input:GetKeyPress(KEY_SPACE) then drawDebug = not drawDebug end -- Toggle debug geometry with space
  109.     if input:GetKeyPress(KEY_F5) then scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/Constraints.xml") end -- Save scene
  110.     local campos=cameraNode.position
  111.     dude.position=Vector3(campos.x, campos.y, dude.position.z)
  112. end
  113.  
  114. function HandlePostRenderUpdate(eventType, eventData)
  115.     if drawDebug then physicsWorld:DrawDebugGeometry() end
  116. end
  117.  
  118. function HandleMouseButtonDown(eventType, eventData)
  119.     local rigidBody = physicsWorld:GetRigidBody(input.mousePosition.x, input.mousePosition.y) -- Raycast for RigidBody2Ds to pick
  120.     if rigidBody ~= nil then
  121.         pickedNode = rigidBody.node
  122.         local staticSprite = pickedNode:GetComponent("StaticSprite2D")
  123.         staticSprite.color = Color(1, 0, 0, 1) -- Temporary modify color of the picked sprite
  124.  
  125.         -- ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with the mouse
  126.         local constraintMouse = pickedNode:CreateComponent("ConstraintMouse2D")
  127.         constraintMouse.target = GetMousePositionXY()
  128.         constraintMouse.maxForce = 1000 * rigidBody.mass
  129.         constraintMouse.collideConnected = true
  130.         constraintMouse.otherBody = dummyBody  -- Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
  131.     end
  132.     SubscribeToEvent("MouseMove", "HandleMouseMove")
  133.     SubscribeToEvent("MouseButtonUp", "HandleMouseButtonUp")
  134. end
  135.  
  136. function HandleMouseButtonUp(eventType, eventData)
  137.     if pickedNode ~= nil then
  138.         local staticSprite = pickedNode:GetComponent("StaticSprite2D")
  139.         staticSprite.color = Color(1, 1, 1, 1) -- Restore picked sprite color
  140.  
  141.         pickedNode:RemoveComponent("ConstraintMouse2D") -- Remove temporary constraint
  142.         pickedNode = nil
  143.     end
  144.     UnsubscribeFromEvent("MouseMove")
  145.     UnsubscribeFromEvent("MouseButtonUp")
  146. end
  147.  
  148. function GetMousePositionXY()
  149.     local screenPoint = Vector3(input.mousePosition.x / graphics.width, input.mousePosition.y / graphics.height, 0)
  150.     local worldPoint = camera:ScreenToWorldPoint(screenPoint)
  151.     return Vector2(worldPoint.x, worldPoint.y)
  152. end
  153.  
  154. function HandleMouseMove(eventType, eventData)
  155.     if pickedNode ~= nil then
  156.         local constraintMouse = pickedNode:GetComponent("ConstraintMouse2D")
  157.         constraintMouse.target = GetMousePositionXY()
  158.     end
  159. end
  160.  
  161. function HandleTouchBegin3(eventType, eventData)
  162.     local rigidBody = physicsWorld:GetRigidBody(eventData["X"]:GetInt(), eventData["Y"]:GetInt()) -- Raycast for RigidBody2Ds to pick
  163.     if rigidBody ~= nil then
  164.         pickedNode = rigidBody.node
  165.         local staticSprite = pickedNode:GetComponent("StaticSprite2D")
  166.         staticSprite.color = Color(1, 0, 0, 1) -- Temporary modify color of the picked sprite
  167.         local rigidBody = pickedNode:GetComponent("RigidBody2D")
  168.  
  169.         -- ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with touch
  170.         local constraintMouse = pickedNode:CreateComponent("ConstraintMouse2D")
  171.         constraintMouse.target = camera:ScreenToWorldPoint(Vector3(eventData["X"]:GetInt() / graphics.width, eventData["Y"]:GetInt() / graphics.height, 0))
  172.         constraintMouse.maxForce = 1000 * rigidBody.mass
  173.         constraintMouse.collideConnected = true
  174.         constraintMouse.otherBody = dummyBody  -- Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
  175.         constraintMouse.dampingRatio = 0
  176.     end
  177.     SubscribeToEvent("TouchMove", "HandleTouchMove3")
  178.     SubscribeToEvent("TouchEnd", "HandleTouchEnd3")
  179. end
  180.  
  181. function HandleTouchMove3(eventType, eventData)
  182.     if pickedNode ~= nil then
  183.         local constraintMouse = pickedNode:GetComponent("ConstraintMouse2D")
  184.         constraintMouse.target = camera:ScreenToWorldPoint(Vector3(eventData["X"]:GetInt() / graphics.width, eventData["Y"]:GetInt() / graphics.height, 0))
  185.     end
  186. end
  187.  
  188. function HandleTouchEnd3(eventType, eventData)
  189.     if pickedNode ~= nil then
  190.         local staticSprite = pickedNode:GetComponent("StaticSprite2D")
  191.         staticSprite.color = Color(1, 1, 1, 1) -- Restore picked sprite color
  192.  
  193.         pickedNode:RemoveComponent("ConstraintMouse2D") -- Remove temporary constraint
  194.         pickedNode = nil
  195.     end
  196.     UnsubscribeFromEvent("TouchMove")
  197.     UnsubscribeFromEvent("TouchEnd")
  198. end
  199.  
  200. -- Create XML patch instructions for screen joystick layout specific to this sample app
  201. function GetScreenJoystickPatchString()
  202.     return
  203.         "<patch>" ..
  204.         "    <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
  205.         "    <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" ..
  206.         "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
  207.         "        <element type=\"Text\">" ..
  208.         "            <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  209.         "            <attribute name=\"Text\" value=\"PAGEUP\" />" ..
  210.         "        </element>" ..
  211.         "    </add>" ..
  212.         "    <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
  213.         "    <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" ..
  214.         "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
  215.         "        <element type=\"Text\">" ..
  216.         "            <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  217.         "            <attribute name=\"Text\" value=\"PAGEDOWN\" />" ..
  218.         "        </element>" ..
  219.         "    </add>" ..
  220.         "</patch>"
  221. end
Advertisement
Add Comment
Please, Sign In to add comment