- Select manual -

Camera

This example shows how to use use a camera component and have it follow a game object. Click to toggle between following the game object and staying stationary.

camera

The setup consists of one bee game object that the camera can follow and one camera game object containing the camera component. The camera component will when active send view and projection updates to the render script.

bee
The bee. Contains:
  • A Sprite component with the bee image.
  • A script that tells the camera wether it should follow the game object or not.
camera
The camera. Contains:
  • A Camera component.
  • A script that controls the camera component.

bee.script

function init(self)
    msg.post(".", "acquire_input_focus")
    go.animate(".", "position.x", go.PLAYBACK_LOOP_PINGPONG, 2000, go.EASING_INOUTQUAD, 10) 
    msg.post("camera", "follow") 
    self.follow = true 
end


function on_input(self, action_id, action)
    if action_id == hash("touch") and action.pressed then 
        self.follow = not self.follow
        if self.follow then
            msg.post("camera", "follow")
        else
            msg.post("camera", "unfollow")
        end
    end
end
  1. Move this game object back and forth across the scene.
  2. Send a message to the camera game object telling it to follow this game object.
  3. Keep track of if the camera is following this game object or not.
  4. Toggle between following and not following the game object when the left mouse button is clicked or the screen is touched.

camera.script

function init(self)
    msg.post("#camera", "acquire_camera_focus") 
end

function on_message(self, message_id, message, sender)
    if message_id == hash("follow") then 
        go.set_parent(".", sender) 
        go.set_position(vmath.vector3(-360, -360, 0)) 
    elseif message_id == hash("unfollow") then 
        go.set_parent("camera", nil, true)
    end
end
  1. Acquire camera focus for the camera component. When a camera has focus it will send view and projection updates to the render script.
  2. Start following the game object that sent the follow message.
  3. This is done by parenting the camera component to the game object that sent the message.
  4. Offset the camera so that it is centering on the game object (360 is half the screen width and height).
  5. Stop following any game object.
  6. This is done removing the parent game object while maintaining the current world transform.

If you want to play with these examples, you can get the project on Github.

Do you want to see more examples? Why not write a few yourself and submit a pull request? We love contributions.

Contribute