Browse Source

Add Urho2D AngelScript sample.

aster2013 11 years ago
parent
commit
501e02f49d
2 changed files with 245 additions and 10 deletions
  1. 47 10
      Bin/Data/LuaScripts/24_Urho2DSprite.lua
  2. 198 0
      Bin/Data/Scripts/24_Urho2DSprite.as

+ 47 - 10
Bin/Data/LuaScripts/24_Urho2DSprite.lua

@@ -1,9 +1,8 @@
 -- Urho2D spriteexample.
 -- This sample demonstrates:
---     - Creating a 2D scene with static sprite
+--     - Creating a 2D scene with sprite
 --     - Displaying the scene using the Renderer subsystem
---     - Handling keyboard to move and zoom camera
-
+--     - Handling keyboard to move and zoom 2D camera
 require "LuaScripts/Utilities/Sample"
 
 local scene_ = nil
@@ -41,7 +40,6 @@ function CreateScene()
     cameraNode = scene_:CreateChild("Camera")
     -- Set an initial position for the camera scene node above the plane
     cameraNode.position = Vector3(0.0, 0.0, -10.0)
-
     local camera = cameraNode:CreateComponent("Camera")
     camera.orthographic = true
 
@@ -49,29 +47,47 @@ function CreateScene()
     local height = graphics.height
     camera:SetOrthoSize(Vector2(width, height))
 
-    local sprite = cache:GetResource("Sprite2D", "Textures/Aster.png")
+    local sprite = cache:GetResource("Sprite2D", "Urho2D/Aster.png")
     if sprite == nil then
         return
     end
 
+    local NUM_SPRITES = 200
     local halfWidth = width * 0.5
     local halfHeight = height * 0.5
-
-    local NUM_SPRITES = 200
     for i = 1, NUM_SPRITES do
-        local spriteNode = scene_:CreateChild("Urho2DSprite")
+        local spriteNode = scene_:CreateChild("StaticSprite2D")
         spriteNode.position = Vector3(Random(-halfWidth, halfWidth), Random(-halfHeight, halfHeight), 0.0)
-        spriteNode:SetScale(0.2 + Random(0.2))
-
+        
         local staticSprite = spriteNode:CreateComponent("StaticSprite2D")
+        -- Set color
         staticSprite.color = Color(Random(1.0), Random(1.0), Random(1.0), 1.0)
+        -- Set blend mode
         staticSprite.blendMode = BLEND_ALPHA
+        -- Set sprite
         staticSprite.sprite = sprite
 
+        -- Set move speed
         spriteNode.moveSpeed = Vector3(Random(-200.0, 200.0), Random(-200.0, 200.0), 0.0)
+        -- Set rotate speed
         spriteNode.rotateSpeed = Random(-90.0, 90.0)
+
         table.insert(spriteNodes, spriteNode)
     end
+
+    local animation = cache:GetResource("Animation2D", "Urho2D/GoldIcon.anm")
+    if animation == nil then
+        return
+    end
+
+    local spriteNode = scene_:CreateChild("AnimatedSprite2D")
+    spriteNode.position = Vector3(0.0, 0.0, -1.0)
+    
+    local animatedSprite = spriteNode:CreateComponent("AnimatedSprite2D")
+    -- Set animation
+    animatedSprite.animation = animation
+    -- Set blend mode
+    animatedSprite.blendMode = BLEND_ALPHA
 end
 
 function CreateInstructions()
@@ -141,4 +157,25 @@ function HandleUpdate(eventType, eventData)
 
     -- Move the camera, scale movement with time step
     MoveCamera(timeStep)
+
+    local halfWidth = graphics.width * 0.5
+    local halfHeight = graphics.height * 0.5
+
+    for _, spriteNode in ipairs(spriteNodes) do
+        local position = spriteNode.position
+        local moveSpeed = spriteNode.moveSpeed
+        local newPosition = position + moveSpeed * timeStep
+        if newPosition.x < -halfWidth or newPosition.x > halfWidth then
+            newPosition.x = position.x
+            moveSpeed.x = -moveSpeed.x
+        end
+
+        if newPosition.y < -halfHeight or newPosition.y > halfHeight then
+            newPosition.y = position.y
+            moveSpeed.y = -moveSpeed.y
+        end
+
+        spriteNode.position = newPosition
+        spriteNode:Roll(spriteNode.rotateSpeed * timeStep)
+    end
 end

+ 198 - 0
Bin/Data/Scripts/24_Urho2DSprite.as

@@ -0,0 +1,198 @@
+// Static 3D scene example.
+// This sample demonstrates:
+//     - Creating a 2D scene with sprite
+//     - Displaying the scene using the Renderer subsystem
+//     - Handling keyboard to move and zoom 2D camera
+
+#include "Scripts/Utilities/Sample.as"
+
+Scene@ scene_;
+Node@ cameraNode;
+Array<Node@> spriteNodes;
+
+void Start()
+{
+    // Execute the common startup for samples
+    SampleStart();
+
+    // Create the scene content
+    CreateScene();
+
+    // Create the UI content
+    CreateInstructions();
+
+    // Setup the viewport for displaying the scene
+    SetupViewport();
+
+    // Hook up to the frame update events
+    SubscribeToEvents();
+}
+
+void CreateScene()
+{
+    scene_ = Scene();
+
+    // Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
+    // show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
+    // is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
+    // optimizing manner
+    scene_.CreateComponent("Octree");
+
+    // Create a scene node for the camera, which we will move around
+    // The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
+    cameraNode = scene_.CreateChild("Camera");
+    // Set an initial position for the camera scene node above the plane
+    cameraNode.position = Vector3(0.0f, 0.0f, -10.0f);
+
+    Camera@ camera = cameraNode.CreateComponent("Camera");
+    camera.orthographic = true;
+
+    uint width = graphics.width;
+    uint height = graphics.height;
+    camera.SetOrthoSize(Vector2(width, height));
+
+    Sprite2D@ sprite = cache.GetResource("Sprite2D", "Urho2D/Aster.png");
+    if (sprite is null)
+        return;
+
+    uint halfWidth = width * 0.5f;
+    uint halfHeight = height * 0.5f;
+    // Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a
+    // quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains
+    // LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll
+    // see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the
+    // same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the
+    // scene.
+    const uint NUM_SPRITES = 200;
+    for (uint i = 0; i < NUM_SPRITES; ++i)
+    {
+        Node@ spriteNode = scene_.CreateChild("StaticSprite2D");
+        spriteNode.position = Vector3(Random(-halfWidth, halfWidth), Random(-halfHeight, halfHeight), 0.0f);
+        
+        StaticSprite2D@ staticSprite = spriteNode.CreateComponent("StaticSprite2D");
+        // Set color
+        staticSprite.color = Color(Random(1.0f), Random(1.0f), Random(1.0f), 1.0f);
+        // Set blend mode
+        staticSprite.blendMode = BLEND_ALPHA;
+        // Set sprite
+        staticSprite.sprite = sprite;
+        
+        spriteNode.vars["MoveSpeed"] = Vector3(Random(-200.0f, 200.0f), Random(-200.0f, 200.0f), 0.0f);
+        spriteNode.vars["RotateSpeed"] = Random(-90.0f, 90.0f);
+
+        spriteNodes.Push(spriteNode);
+    }
+
+    Animation2D@ animation = cache.GetResource("Animation2D", "Urho2D/GoldIcon.anm");
+    if (animation is null)
+        return;
+    Node@ spriteNode = scene_.CreateChild("AnimatedSprite2D");
+    spriteNode.position = Vector3(0.0f, 0.0f, -1.0f);
+
+    AnimatedSprite2D@ animatedSprite = spriteNode.CreateComponent("AnimatedSprite2D");
+    // Set animation
+    animatedSprite.animation = animation;
+    // Set blend mode
+    animatedSprite.blendMode = BLEND_ALPHA;
+}
+
+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.";
+    instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
+
+    // Position the text relative to the screen center
+    instructionText.horizontalAlignment = HA_CENTER;
+    instructionText.verticalAlignment = VA_CENTER;
+    instructionText.SetPosition(0, ui.root.height / 4);
+}
+
+void SetupViewport()
+{
+    // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
+    // at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
+    // use, but now we just use full screen and default render path configured in the engine command line options
+    Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
+    renderer.viewports[0] = viewport;
+}
+
+void MoveCamera(float timeStep)
+{
+    // Do not move if the UI has a focused element (the console)
+    if (ui.focusElement !is null)
+        return;
+
+    // Movement speed as world units per second
+    const float MOVE_SPEED = 400.0f;
+    
+    // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
+    // Use the TranslateRelative() function to move relative to the node's orientation. Alternatively we could
+    // multiply the desired direction with the node's orientation quaternion, and use just Translate()
+    if (input.keyDown['W'])
+        cameraNode.TranslateRelative(Vector3(0.0f, 1.0f, 0.0f) * MOVE_SPEED * timeStep);
+    if (input.keyDown['S'])
+        cameraNode.TranslateRelative(Vector3(0.0f, -1.0f, 0.0f) * MOVE_SPEED * timeStep);
+    if (input.keyDown['A'])
+        cameraNode.TranslateRelative(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
+    if (input.keyDown['D'])
+        cameraNode.TranslateRelative(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
+
+    if (input.keyDown[KEY_PAGEUP])
+    {
+        Camera@ camera = cameraNode.GetComponent("Camera");
+        camera.zoom = camera.zoom * 1.01f;
+    }
+    
+    if (input.keyDown[KEY_PAGEDOWN])
+    {
+        Camera@ camera = cameraNode.GetComponent("Camera");
+        camera.zoom = camera.zoom * 0.99f;
+    }
+}
+
+void SubscribeToEvents()
+{
+    // Subscribe HandleUpdate() function for processing update events
+    SubscribeToEvent("Update", "HandleUpdate");
+}
+
+void HandleUpdate(StringHash eventType, VariantMap& eventData)
+{
+    // Take the frame time step, which is stored as a float
+    float timeStep = eventData["TimeStep"].GetFloat();
+
+    // Move the camera, scale movement with time step
+    MoveCamera(timeStep);
+
+    float halfWidth = graphics.width * 0.5f;
+    float halfHeight = graphics.height * 0.5f;
+
+    // Go through all sprites
+    for (uint i = 0; i < spriteNodes.length; ++i)
+    {
+        Node@ spriteNode = spriteNodes[i];
+
+        Vector3 moveSpeed = spriteNode.vars["MoveSpeed"].GetVector3();
+        Vector3 newPosition = spriteNode.position + moveSpeed * timeStep;
+        
+        if (newPosition.x < -halfWidth || newPosition.x > halfWidth)
+        {
+            newPosition.x = spriteNode.position.x;
+            moveSpeed.x = -moveSpeed.x;
+            spriteNode.vars["MoveSpeed"] = moveSpeed;
+        }
+
+        if (newPosition.y < -halfHeight || newPosition.y > halfHeight)
+        {
+            newPosition.y = spriteNode.position.y;
+            moveSpeed.y = -moveSpeed.y;
+            spriteNode.vars["MoveSpeed"] = moveSpeed;
+        }
+
+        spriteNode.position = newPosition;
+        spriteNode.Roll(spriteNode.vars["RotateSpeed"].GetFloat() * timeStep);
+    }
+}
+