IOpenSpaceAPI

Kind of class:public interface
Package:com.smartfoxserver.openspace.engine.control
Inherits from:none
Implemented by:
Version:2.1.0
Author:The gotoAndPlay() Team
http://www.openspace-engine.com
http://www.smartfoxserver.com
http://www.gotoandplay.it
Classpath:com.smartfoxserver.openspace.engine.control.IOpenSpaceAPI
File last modified:Thursday, 05 September 2013, 18:04:19
The OpenSpace Application Programming Interface.

This interface is implemented by both Flex and Flash OpenSpace components and it exposes all the public properties and methods accessible by the developers to interact with the OpenSpace Engine at runtime.

NOTE: in the provided examples, openSpace always indicates an OpenSpace instance.

NAMING CONVENTIONS for this API reference:
  • OpenSpace: the OpenSpace client component (both Flex and Flash versions)
  • OpenSpace Extension: the SmartFoxServer server-side extension used by the OpenSpace Engine to perform various tasks (map loading, pathfinding, etc.); check the OpenSpace installation guide in the online documentation
  • OpenSpace Editor: the OpenSpace offline map editing application, required to build maps and inventories that will be loaded by the OpenSpace component
  • PLAY MODE: OpenSpace default mode, in which users can make their avatars move around in the environment, interact with map items and other avatars, etc
  • EDIT MODE: OpenSpace runtime map editing mode, in which users can edit maps by dragging and dropping inventory items; see enterEditMode method for additional informations
Events broadcasted to listeners:
  • MapInteractionEvent with type: TILE_CLICK
    • Dispatched when a tile on the map is clicked.
  • MapInteractionEvent with type: TILE_ROLL_OVER
    • Dispatched when the mouse rolls over a tile on the map.
  • MapInteractionEvent with type: TILE_ROLL_OUT
    • Dispatched when the mouse rolls out of a tile on the map.
  • MapInteractionEvent with type: SKIN_CLICK
    • Dispatched when a skin is clicked.
  • MapInteractionEvent with type: SKIN_ROLL_OVER
    • Dispatched when the mouse rolls over a skin.
  • MapInteractionEvent with type: SKIN_ROLL_OUT
    • Dispatched when the mouse rolls out of a skin.
  • AvatarEvent with type: CLICK
    • Dispatched when an avatar (main sprite only) is clicked.
  • AvatarEvent with type: ROLL_OVER
    • Dispatched when the mouse rolls over an avatar (main sprite only).
  • AvatarEvent with type: ROLL_OUT
    • Dispatched when the mouse rolls out of an avatar (main sprite only).
  • OpenSpaceEvent with type: INITIALIZED
    • Dispatched when OpenSpace is initialized.
  • OpenSpaceEvent with type: MAP_LOADED
    • Dispatched when a map data file is loaded and parsed successfully.
  • OpenSpaceEvent with type: MAP_ERROR
    • Dispatched when a non-blocking error occurs while loading a map.
  • OpenSpaceEvent with type: MAP_FAILURE
    • Dispatched when a blocking error occurs while loading/parsing/rendering a map.
  • OpenSpaceEvent with type: MAP_CREATION_PROGRESS
    • Dispatched when a progress occurs during the tiles instances creation process.
  • OpenSpaceEvent with type: MAP_RENDERED
    • Dispatched when the tiles instances creation process is completed and the isometric environment described by the loaded map has been rendered on the stage.
  • OpenSpaceEvent with type: RESET
    • Dispatched when OpenSpace is reset.
  • OpenSpaceEvent with type: ANIMATION_START
    • Dispatched when the map animation (pan/zoom/scroll) starts.
  • OpenSpaceEvent with type: ANIMATION_END
    • Dispatched when the map animation (pan/zoom/scroll) ends.
  • OpenSpaceEvent with type: INVENTORY_LOADED
    • Dispatched when the inventory data is returned by the OpenSpace Extension and it is parsed successfully.
  • OpenSpaceEvent with type: INVENTORY_ERROR
    • Dispatched when an error occurs while loading or parsing the inventory data.
  • OpenSpaceEvent with type: EDIT_MODE_ENTERED
    • Dispatched when EDIT MODE is entered at runtime.
  • OpenSpaceEvent with type: EDIT_MODE_LEFT
    • Dispatched when EDIT MODE is left at runtime.
  • OpenSpaceEvent with type: MAP_UPDATE_ERROR
    • Dispatched when an error occurs in the OpenSpace Extension while updating a map.
  • OpenSpaceEvent with type: MAP_UPDATED
    • Dispatched when the current map is updated by another user.
  • AvatarEvent with type: AVATAR_CREATED
    • Dispatched when an avatar is created.
  • AvatarEvent with type: START_MOVEMENT
    • Dispatched when an avatar standing on a tile starts moving.
  • AvatarEvent with type: STOP_MOVEMENT
    • Dispatched when a moving avatar stops on a tile.
  • AvatarEvent with type: ENTER_TILE
    • Dispatched when an avatar enters a tile during its movement.
  • AvatarEvent with type: LEAVE_TILE
    • Dispatched when an avatar leaves a tile during its movement.

Summary


Instance properties
  • version : String
    • The OpenSpace version number in the format "x.y.z | i.j.k".
  • configPath (value:String) : String
    • The path of the OpenSpace client-side configuration file.
  • skinAppDomain (value:ApplicationDomain) : ApplicationDomain
    • The application domain containing the skin classes definitions.
  • bgAppDomain (value:ApplicationDomain) : ApplicationDomain
    • The application domain containing the background/foreground parts classes definitions.
  • avatarAppDomain (value:ApplicationDomain) : ApplicationDomain
    • The application domain containing the avatar classes definitions.
  • isEditMode : Boolean
    • The runtime map editing status.
  • traceEnabled (value:Boolean) : Boolean
    • Enable console trace of logged data (informations, warnings and errors) for debug purposes.
  • userInteractionEnabled (value:Boolean) : Boolean
    • Enable/disable user interaction.
  • preAvatarMoveValidator (func:Function) : Function
    • Custom avatar movement validator function.
  • tileDropValidator (func:Function) : Function
    • Custom tile drop validator function.
  • mapScrollingEnabled (value:Boolean) : Boolean
    • Enable/disable map scrolling on player's avatar movement.
Instance methods
  • init (smartFoxClient:*, customItemSelector:AbstractMapItemSelector = null) : void
    • Initialize OpenSpace.
  • loadMap (room:*, password:String = "") : void
    • Join a SmartFoxServer Room and load the corresponding map data.
  • renderMap (params:MapCenteringParams = null) : void
    • Render a loaded map.
  • unloadMap : void
    • Unload current map.
  • centerViewOnCoords (mapCenteringParams:MapCenteringParams, showAnimation:Boolean = true) : void
    • Center the viewport on map tile coordinates.
  • panView (dx:int, dy:int, overrideLimits:Boolean = false, showAnimation:Boolean = true) : void
    • Pan the viewport.
  • zoomView (factor:Number, showAnimation:Boolean = true, mapCenteringParams:MapCenteringParams = null) : void
    • Zoom the viewport.
  • loadInventory (projectId:String = "", filterParams:Object = null) : void
    • Load an inventory.
  • getInventoryItemSprite (itemId:String, itemDir:int) : Sprite
    • Retrieve the graphics of an inventory item.
  • getInventoryItemCount (itemId:String) : int
    • Retrieve the number of instances of an inventory item placed on the current map.
  • enterEditMode : void
    • Leave PLAY MODE and enable EDIT MODE.
  • dragInventoryItem (itemId:String, itemDir:int, dragInitiator:*, event:MouseEvent, tileInstName:String = null, tileTriggers:Array = null) : void
    • Start a drag action of an inventory item from an external source.
  • leaveEditMode (saveChanges:Boolean) : void
    • Leave EDIT MODE and go back to PLAY MODE.
  • getTileByCoordinates (coords:Position3D) : Tile
    • Retrieve a reference to a Tile object on current the map by means of its coordinates.
  • getTileByName (tileName:String) : Tile
    • Retrieve a reference to a Tile object on the current map by means of its instance name.
  • getGroup (groupId:String) : Array
    • Retrieve the list of Tile objects which are part of the specified group.
  • getSkinByName (tileName:String, skinName:String) : DisplayObject
    • Retrieve a skin display object contained in a specific Tile object on the current map by means of its instance name.
  • getAllSkinsByName (name:String) : Array
    • Retrieve an array of skin display objects contained on the current map by means of their common instance name.
  • getBackgroundParts : Array2
    • Retrieve an array of references to the display objects making up the background of the current map.
  • getForegroundParts : Array2
    • Retrieve an array of references to the display objects making up the foreground of the current map.
  • setCustomMapLimits (limits:Rectangle) : void
    • Set the limits of the current map.
  • getMapSize : MapSize
    • Get the size of the current map.
  • checkTileWalkability (coords:Position3D) : Boolean
    • Check if player's avatar can walk on the tile corresponding to passed coordinates.
  • showWireframe (showFill:Boolean = false) : void
    • Show the structure of tiles on the current map.
  • hideWireframe : void
    • Hide the structure of tiles on the current map.
  • createMyAvatar (params:AvatarCreationParams) : void
    • Create the player's avatar.
  • removeMyAvatar : void
    • Remove the player's avatar.
  • getMyAvatar : Avatar
    • Get a reference to the player's main avatar.
  • getMyGhostAvatar : Avatar
    • Get a reference to the player's ghost avatar.
  • setMyAvatarSkin (skin:Object) : void
    • Set the skin of the player's avatar.
  • setMyAvatarState (state:Object) : void
    • Change the state of the player's avatar.
  • setMyAvatarAction (action:Object) : void
    • Make the player's avatar perform a custom action.
  • setMyAvatarAnimationTime (animationTime:int) : void
    • Change the duration of the player's avatar movement from tile to tile along N/E/S/W directions.
  • moveMyAvatar (coords:Position3D, disableUserInteraction:Boolean = false) : void
    • Make the player's avatar walk to a tile on the map.
  • stopMyAvatar : void
    • Stop the player's avatar while moving.
  • stopAvatarLocal (avatarId:int) : void
    • Stop a moving avatar on the current client only.
  • teleportMyAvatar (coords:Position3D, direction:int = -1, applyHeightCorrection:Boolean = true, showEffect:Boolean = true) : void
    • Make the player's avatar appear on a new tile on the map instantly.
  • centerViewOnMyAvatar (applyHeightCorrection:Boolean = true, showAnimation:Boolean = true) : void
    • Center the viewport on the player's avatar.
  • zoomOnMyAvatar (factor:Number, applyHeightCorrection:Boolean = true, showAnimation:Boolean = true) : void
    • Zoom the viewport on the player's avatar.
  • getMyAvatarCurrentTile : Tile
    • Get a reference to the tile on which the player's avatar is currently standing.
  • getAvatarById (avatarId:int) : Avatar
    • Get a reference to any user's main avatar.
  • getGhostAvatarById (avatarId:int) : Avatar
    • Get a reference to any user's ghost avatar.

Instance properties

avatarAppDomain

public avatarAppDomain:ApplicationDomain
(read,write)

The application domain containing the avatar classes definitions.
When an external avatar library (a SWF file containing the Avatar classes used in the virtual world), all class definitions in the loaded file/s are stored in the application domain specified by the applicationDomain property of the flash.system.LoaderContext object passed as context parameter of the used flash.display.Loader object's load method.
If a specific application domain is used (instead of the default ApplicationDomain.currentDomain), it must be passed through this property to make OpenSpace able to retrieve the Avatar classes and instantiate them at runtime.
NOTE 1: the passed application domain must have its parent domain set to the current domain in which the code is executing (see example below), otherwise a "Class must extend Avatar" exception will be thrown when creating the avatars.
NOTE 2: this property must be set before any avatar is created; as avatars of users already on a map are created during the rendering process of that map (while player's avatar is created when the createMyAvatar method is called only), this property should be set before the renderMap method is called.
Example:
  • Load an external SWF file containing avatar definitions, store them in a separate application domain and assign it to OpenSpace:
    function loadAvatars(avatarsLibraryFileName:String):void
    {
        // Create a new application domain for avatar classes
        // NOTE 1: avatarLibAppDomain is a class property (can't be local as we must access it on loading completion)
        // NOTE 2: the parent domain is set to the current domain in which the code is executing
        avatarLibAppDomain = new ApplicationDomain(ApplicationDomain.currentDomain)
    
        // Create instance of Loader object
        var loader:Loader = new Loader()
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onAvatarsLibLoaded)
    
        // Create URLRequest object passing the path to the avatars library SWF file
        var request:URLRequest = new URLRequest("libraries/" + avatarsLibraryFileName)
    
        // Create a LoaderContext object setting the target application domain
        var context:LoaderContext = new LoaderContext(false, avatarLibAppDomain)
    
        // Load SWF file
        loader.load(request, context)
    }
    
    function onAvatarsLibLoaded(evt:Event):void
    {
        // Set the OpenSpace avatarAppDomain property
        openSpace.avatarAppDomain = avatarLibAppDomain
    
        // Now we can render the previously loaded map
        openSpace.renderMap()
    }

bgAppDomain

public bgAppDomain:ApplicationDomain
(read,write)

The application domain containing the background/foreground parts classes definitions.
When using one or more external background libraries (SWF files containing the sprites/movieclips used to compose the map background and/or foreground), all definitions in the loaded file/s are stored in the application domain specified by the applicationDomain property of the flash.system.LoaderContext object passed as context parameter of the used flash.display.Loader object's load method.
If a specific application domain is used (instead of the default ApplicationDomain.currentDomain), it must be passed through this property to make OpenSpace able to retrieve the map background parts and render them at runtime.
NOTE 1: this property must be set before rendering a map (see renderMap method). If not set, the default value ApplicationDomain.currentDomain is used.
NOTE 2: if separate SWF files are used for tiles' skins and map background parts, all of them must be loaded and the respective application domains set before the map rendering is launched.
Example:
  • Load an external SWF file containing background parts, store definitions in a separate application domain and assign it to OpenSpace:
    function loadMapBackground(bgLibraryFileName:String):void
    {
        // Create instance of Loader object
        var loader:Loader = new Loader()
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onMapBackgroundLibLoaded)
    
        // Create URLRequest object passing the path to the background parts library SWF file
        var request:URLRequest = new URLRequest("libraries/" + bgLibraryFileName)
    
        // Create a LoaderContext object setting the target application domain
        // NOTE: swfLibrariesAppDomain is a class property (can't be local as we must access it on loading completion)
        var context:LoaderContext = new LoaderContext(false, swfLibrariesAppDomain)
    
        // Load SWF file
        loader.load(request, context)
    }
    
    function onMapBackgroundLibLoaded(evt:Event):void
    {
        // Set the OpenSpace bgAppDomain property
        openSpace.bgAppDomain = swfLibrariesAppDomain
    
        // Now we can render the previously loaded map
        openSpace.renderMap()
    }

configPath

public configPath:String
(read,write)

The path of the OpenSpace client-side configuration file.
This path is relative to the SWF file which contains the OpenSpace instance. The default value is config/OpenSpace_client.xml.
This property can be set at author-time in the Properties Panel of the OpenSpace component.
NOTE: the configuration path must be set before calling the init method.

The OpenSpace client-side configuration parameters are described in the Client configuration tutorial.
Example:
  • Set the configuration path:
    openSpace.configPath = "clientConfig/OpenSpace.xml"

isEditMode

public isEditMode:Boolean
(read)

The runtime map editing status.
If true, OpenSpace is currently in EDIT MODE; if false, OpenSpace is currently in PLAY MODE.
Example:
  • Check if runtime map editing is in progress:
    trace("Is map editing in progress?", openSpace.isEditMode)

mapScrollingEnabled

public mapScrollingEnabled:Boolean
(read,write)

Enable/disable map scrolling on player's avatar movement.
When this property is set to false, the player's avatar does not trigger the map scrolling animation when it moves beyond the scroll sensor area limits defined in the OpenSpace client-side configuration (see the Scrolling parameters section).
OpenSpace sets this property to true each time a map is rendered after loading.
Example:
  • Disable map scrolling:
    openSpace.mapScrollingEnabled = false

preAvatarMoveValidator

public preAvatarMoveValidator:Function
(write)

Custom avatar movement validator function.
This function is called by OpenSpace before the player's avatar movement is started, right after the player has clicked on a tile or pressed an arrow key on the keyboard (if enabled).
The target Tile object is passed as parameter, and the function is supposed to return a boolean value.
If false is returned, OpenSpace will ignore the player's action; otherwise OpenSpace will follow the default behavior (the path to the target tile will be requested to the OpenSpace Extension).
Usage note:
  • Implementing this function can be useful to inhibit the player's avatar movement on the map without disabling user interaction (the player can still click skins/tiles/avatars and the respective events are fired, but he can't make his avatar move around).

    Another possible use case for this property derives from the typical scenario where avatars are allowed to sit on chairs, benches, etc.
    Making an avatar sit on a chair is quite simple in OpenSpace: a chair is usually a non-walkable tile with a click trigger assigned to its skin; when the player clicks on the skin and the event is fired, we can call the createMyAvatar method, passing the destination coordinates, the direction that the avatar must face and a state object which will cause the proper graphics to be displayed (see the Avatar class).
    Now, how to make the avatar stand-up later? If the player clicks on a new tile, as the chair's tile is non-walkable, no path will be found. By implementing the preAvatarMoveValidator we can intercept the click, teleport the avatar back to a walkable tile near the chair and return true to OpenSpace, which will then execute the pathfinding algorithm to send the avatar to the requested tile.
Example:
  • Set a movement validator function:
    openSpace.preAvatarMoveValidator = function(tile:Tile):Boolean
                                        {
                                            var result:Boolean
    
                                            // TODO: check if the player is allowed to send the avatar
                                            // to the target tile and return the result
    
                                            return result
                                        }

skinAppDomain

public skinAppDomain:ApplicationDomain
(read,write)

The application domain containing the skin classes definitions.
When using one or more external skins libraries (SWF files containing the sprites/movieclips used as skins in tiles), all definitions in the loaded file/s are stored in the application domain specified by the applicationDomain property of the flash.system.LoaderContext object passed as context parameter of the used flash.display.Loader object's load method.
If a specific application domain is used (instead of the default ApplicationDomain.currentDomain), it must be passed through this property to make OpenSpace able to retrieve the tiles' skins and render them at runtime.
NOTE 1: this property must be set before rendering a map (see renderMap method) or before requesting an inventory item sprite (see getInventoryItemSprite method). If not set, the default value ApplicationDomain.currentDomain is used.
NOTE 2: if separate SWF files are used for tiles' skins and map backgrounds, all of them must be loaded and the respective application domains set before the map rendering is launched.
Example:
  • Load an external SWF file containing skins, store definitions in a separate application domain and assign it to OpenSpace:
    function loadMapSkins(skinsLibraryFileName:String):void
    {
        // Create instance of Loader object
        var loader:Loader = new Loader()
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onMapSkinsLibLoaded)
    
        // Create URLRequest object passing the path to the skins library SWF file
        var request:URLRequest = new URLRequest("libraries/" + skinsLibraryFileName)
    
        // Create a LoaderContext object setting the target application domain
        // NOTE: swfLibrariesAppDomain is a class property (can't be local as we must access it on loading completion)
        var context:LoaderContext = new LoaderContext(false, swfLibrariesAppDomain)
    
        // Load SWF file
        loader.load(request, context)
    }
    
    function onMapSkinsLibLoaded(evt:Event):void
    {
        // Set the OpenSpace skinAppDomain property
        openSpace.skinAppDomain = swfLibrariesAppDomain
    
        // Now we can render the previously loaded map
        openSpace.renderMap()
    }

tileDropValidator

public tileDropValidator:Function
(write)

Custom tile drop validator function.
This function is called by OpenSpace when the player is dragging an item on the map during runtime editing.
The Tile on which the drop will eventually occur is passed as parameter, and the function is supposed to return a boolean value.
If false is returned, the drop action is not allowed. If a supertile is being dragged, this function is called for each tile of the drop area.
NOTE: this validation function must be set before calling the init method.
Example:
  • Set a tile drop validator function:
    openSpace.tileDropValidator = function(tile:Tile):Boolean
                                    {
                                        var result:Boolean
    
                                        // TODO: check if the player is allowed to drop an item
                                        // on the target tile and return the result
    
                                        return result
                                    }

traceEnabled

public traceEnabled:Boolean
(read,write)

Enable console trace of logged data (informations, warnings and errors) for debug purposes.
This property can be set at author-time in the Properties Panel of the OpenSpace component.
Example:
  • Enable the console trace:
    openSpace.traceEnabled = true
See also:

userInteractionEnabled

public userInteractionEnabled:Boolean
(read,write)

Enable/disable user interaction.
When this property is set to false, the player is not able to interact with OpenSpace using the available control methods (mouse and/or keyboard - see OpenSpace client-side configuration).
In PLAY MODE, enabling user interaction has effect if the player's avatar is currently on the map.
Disabling user interaction doesn't affect the "hand cursor" visual feedback (if enabled - see <UseHandCursor> parameter in the OpenSpace client-side configuration): clickable tiles will still show the hand cursor.
Usage note:
  • When user interaction is disabled, also tile/skin/avatar click events are not triggered. This might prevent developers from implementing specific use cases.
    For example, we want the player's avatar not to move when the player clicks on a tile, but still let the player interact with the environment (with an NPC, for example). In this scenario, instead of disabling the user interaction using this property, we may implement the preAvatarMoveValidator function.
Events broadcasted to listeners:
  • MapInteractionEvent with type: TILE_CLICK
    • Dispatched when a tile on the map is clicked.
  • MapInteractionEvent with type: TILE_ROLL_OVER
    • Dispatched when the mouse rolls over a tile on the map.
  • MapInteractionEvent with type: TILE_ROLL_OUT
    • Dispatched when the mouse rolls out of a tile on the map.
  • MapInteractionEvent with type: SKIN_CLICK
    • Dispatched when a skin is clicked.
  • MapInteractionEvent with type: SKIN_ROLL_OVER
    • Dispatched when the mouse rolls over a skin.
  • MapInteractionEvent with type: SKIN_ROLL_OUT
    • Dispatched when the mouse rolls out of a skin.
  • AvatarEvent with type: CLICK
    • Dispatched when an avatar (main sprite only) is clicked.
  • AvatarEvent with type: ROLL_OVER
    • Dispatched when the mouse rolls over an avatar (main sprite only).
  • AvatarEvent with type: ROLL_OUT
    • Dispatched when the mouse rolls out of an avatar (main sprite only).
Example:
  • Disable user interaction:
    openSpace.userInteractionEnabled = false

version

public version:String
(read)

The OpenSpace version number in the format "x.y.z | i.j.k".
The meaning of the six numbers is:
x = client major version
y = client minor version
z = client revision
i = server-side Extension major version
j = server-side Extension minor version
k = server-side Extension revision
The OpenSpace Extension version is available after initialization only (see init method).
Example:
  • Trace the OpenSpace version:
    trace("OpenSpace version:",openSpace.version)
See also:

Instance methods

centerViewOnCoords

public function centerViewOnCoords (
mapCenteringParams:MapCenteringParams, showAnimation:Boolean = true) : void

Center the viewport on map tile coordinates.
Parameters:
mapCenteringParams:
an object containing the map coordinates to be centered.
showAnimation :
if true, a scrolling animation from the current viewport position to the centered position is shown; if false, the viewport is centered immediately. In both cases, the relevant camera parameters from the OpenSpace client-side configuration are applied.
Events broadcasted to listeners:
  • OpenSpaceEvent with type: ANIMATION_START
    • Dispatched when the map animation (pan/zoom/scroll) starts.
  • OpenSpaceEvent with type: ANIMATION_END
    • Dispatched when the map animation (pan/zoom/scroll) ends.
Example:
  • Center viewport on the tile corresponding to coordinates (12,7):
    // Set destination coordinates
    var coords:mapCenteringParams = new mapCenteringParams(12, 7)
    
    // Center view
    openSpace.centerViewOnCoords(coords)

centerViewOnMyAvatar

public function centerViewOnMyAvatar (
applyHeightCorrection:Boolean = true, showAnimation:Boolean = true) : void

Center the viewport on the player's avatar.
When centering the viewport, map boundaries are taken into account to avoid showing a blank portion of the map.
OpenSpace ignores this action if the player's avatar is not on the map.
Parameters:
applyHeightCorrection:
if false, viewport is centered on the target tile (in other words at the avatar's feet); if true, the avatar's movieclip height is taken into account in order to center the avatar in the viewport properly.
showAnimation :
if true, a scrolling animation from the current viewport position to the centered position is shown; if false, the viewport is centered immediately. In both cases, the relevant camera parameters from the OpenSpace client-side configuration are applied.
Events broadcasted to listeners:
  • OpenSpaceEvent with type: ANIMATION_START
    • Dispatched when the map animation (pan/zoom/scroll) starts.
  • OpenSpaceEvent with type: ANIMATION_END
    • Dispatched when the map animation (pan/zoom/scroll) ends.
Example:
  • Center the viewport on the player's avatar:
    openSpace.centerViewOnMyAvatar()

checkTileWalkability

public function checkTileWalkability (
coords:Position3D) : Boolean

Check if player's avatar can walk on the tile corresponding to passed coordinates.
This method differs from the simple Tile.walkable property, which is avatar-independent and indicates the default tile walkability, because it also takes into account the player's avatar type.
Tile overall walkability is affected by the avatar type in the following ways:
  • avatar stature: if a tile is stacked upon another with a Tile.bottomElevation value greater than 0, this creates an underpass; if the stature of the avatar is greater than the underpass height (corresponding to the Tile.bottomElevation value), the avatar won't be allowed to step on the base tile;
  • tile terrain: if the Tile.terrain property is set on a certain tile, only avatars allowed to walk on that terrain can step on that tile.
Avatar stature and allowed terrains are defined in the OpenSpace server-side configuration. If these settings are not used, default tile walkability is returned.
Parameters:
coords:
a Position3D object containing the tile coordinates; if -1 is passed as pz coordinate, the top tile of the (px,py) stack is returned.
Returns:
  • true if the player's avatar can walk on the tile corresponding to passed coordinates; false if the avatar is not allowed to walk on the tile, or if it doesn't exist when the method is called.
Example:
  • Check the overall walkability of the (23,17) tile:
    var coords:Position3D = new Position3D(0,0)
    
    trace("Is tile walkable by default?", openSpace.getTileByCoordinates(coords).walkable)
    trace("Is tile globally walkable?", openSpace.checkTileWalkability(coords))

createMyAvatar

public function createMyAvatar (
params:AvatarCreationParams) : void

Create the player's avatar.
An avatar of the selected type (passed to this method by means of the AvatarCreationParams.type property) is created by instantiating the classes declared in the mainClass and ghostClass (optional) attributes of the <AvatarType/> tag in the OpenSpace server-side configuration. See the Avatar class for more informations.
The avatar creation process requires that all avatar classes definitions are available in the avatarAppDomain application domain.
Creating an avatar for the player is not mandatory; for example guest users might be allowed to enter the virtual world without an avatar assigned: they will be able explore the maps using the pan and zoom features (see panView and zoomView methods), but the interaction with the map items will be inhibited because they don't have their own avatar inside the world.
Avatars can be created right after a map has been loaded (OpenSpaceEvent.MAP_LOADED event received), or after it has been rendered (OpenSpaceEvent.MAP_RENDERED event received). In the first case the avatar will be already on the map when it is displayed upon rendering completion (for example, the avatar will fade-in together with the map).
The avatar creation is broadcasted to all the users in the SmartFoxServer Room corresponding to the current map: in this way the player's avatar can be rendered by all the OpenSpace clients.
An avatar can be created on a globally non-walkable tile (see the checkTileWalkability method), except in case of underpasses when the avatar stature exceed the underpass height.
An avatar can be removed from the map after the creation by means of the removeMyAvatar method.
If an avatar is created and then this method is called again, the previous avatar is substituted by the new one.
Parameters:
params:
an AvatarCreationParams object containing the mandatory and optional parameters for the initial configuration of the player's avatar.
Events broadcasted to listeners:
  • AvatarEvent with type: AVATAR_CREATED
    • Dispatched when an avatar is created.
Throws:
Example:
  • Create an avatar of type "demo"; no position is passed, so that the avatar will be placed on one of the map's access points:
    var params:AvatarCreationParams = new AvatarCreationParams()
    params.type = "demo"
    params.name = "Jack"
    params.direction = 3
    params.centerViewport = true
    
    var initialSkin:Object = {}
    initialSkin.sex = "m"
    initialSkin.hat = "cowboy"
    
    params.skin = initialSkin
    
    openSpace.createMyAvatar(params)

dragInventoryItem

public function dragInventoryItem (
itemId:String, itemDir:int, dragInitiator:*, event:MouseEvent, tileInstName:String = null, tileTriggers:Array = null) : void

Start a drag action of an inventory item from an external source.
OpenSpace is in charge of handling all the drag&drop operations which involve the map, both internal (as described in the enterEditMode method) and external (a new item dragged over the map).
In order to give the player full map editing capabilities, when EDIT MODE is enabled the application should display the available inventory items that the player can drag and drop on the map. The loadInventory and getInventoryItemSprite methods allow the creation of the inventory items list (usually a separate component in the application interface, like a list or a datagrid), while this method is used to start the drag action when the player clicks on one of the items.
When the drag action is initiated, OpenSpace creates an instance of the desired inventory item, places it on the stage above the drag initiator (the copy of the item in the inventory) and hooks it to the mouse pointer.
When an item is dragged over the map, tiles give a visual feedback highlighting the areas where drop is or isn't allowed, using different colors. Color and alpha values can be customized in the OpenSpace client-side configuration.

IMPORTANT NOTE: during runtime map editing, an inventory item can be dragged on a map if its project id matches the map project id only.
Parameters:
itemId :
the id of the inventory item to be dragged.
itemDir :
the specific view of the inventory item to be dragged (see the InventoryItem.directions property).
dragInitiator:
the display object which initiates the drag; it is usually a copy of the inventory item obtained by calling the getInventoryItemSprite method and shown in the application interface (for example in the inventory list).
event :
the flash.event.MouseEvent that contains the mouse information for the start of the drag; it is usually the mouse-down event caused by the player clicking on the drag initiator.
tileInstName :
if the inventory item to be dragged is of type InventoryItem.TYPE_TILE, an optional custom name can be assigned to the Tile instance that will be created once the item is dropped on the map, so that it can be later retrieved by means of the getTileByName method (optional). In order to avoid messing with instance names, if a tile with the same name already exists on the map, the passed name will be ignored and won't be assigned to the new tile being created. In order to check if an instance name is already in use, call the getTileByName method before starting the drag action.
tileTriggers :
if the inventory item to be dragged is of type InventoryItem.TYPE_TILE, an optional list of Trigger objects can be assigned to the tile that will be created once the item is dropped on the map. The assigned triggers will cause the related MapInteractionEvent to be fired in PLAY MODE.
Example:
  • The following code shows an example of MouseEvent.MOUSE_DOWN event listener added to the selected inventory item in the application's interface; when clicked the drag action is initiated.
    For simplicity, direction 0 of the inventory item is considered. An application should allow the player choose the appropriate item view he wants to drag before the drag action is initiated.
    function onInventoryItemMouseDown(e:MouseEvent):void
    {
        // Retrive inventory item data from the selected item in the inventory list
        var itemData:InventoryItem = ls_inventory.selectedItem.item
    
        // Check if the item is available by means of the custom 'quantity' property added before;
        // if available, start the drag action (itemSprite is the display object
        // representing the inventory item on the stage)
        if (itemData.quantity > 0)
            openSpace.dragInventoryItem(itemData.id, itemData.directions[0], itemSprite, e)
    }

enterEditMode

public function enterEditMode (
) : void

Leave PLAY MODE and enable EDIT MODE.
A map can be edited if it has been flagged as editable inside the OpenSpace Editor. When EDIT MODE is entered, standard player interaction is disabled and all the avatars are removed from the environment. The player can now add items to the map by means of a drag&drop action and select/move/remove items already on the map.
During map editing the player can click a map item to select it. Only map items with an inventory id assigned can be selected. When an item is selected, OpenSpace displays the map item selector instance passed to the init method (or the default selector if null was passed), which can be useful to display additional item informations or additional controls (for example a Remove button).
Selected (or selectable) map items can be dragged to a different location on the map. Please notice that when the drag action starts, the item is actually removed from the map: if the player then drops it on an invalid location, the item will be lost and the user will need to drag it from the inventory again (see dragInventoryItem method).
During the item drag, tiles provide a visual feedback highlighting the areas where drop is or isn't allowed, using different colors. Color and alpha values can be customized in the OpenSpace client-side configuration.
Items on the map can't be rotated in-place: the player must remove the item, select it in an external inventory container (for example a list or a datagrid in the application interface), choose the desired rotation angle (see the getInventoryItemSprite method) and drag it back on the map.

NOTE 1: map editing doesn't happen in realtime. This means that all changes are saved at once and sent to the other users when the leaveEditMode method is called. When the other users are informed that the current map has been changed, interaction is suspended and the map must be reloaded.

NOTE 2: OpenSpace doesn't prevent two or more users from editing the same map at the same time: if, for example, user A and user B both initiate the runtime map editing, and B commits hs changes before A, the client of user A will receive the update event from B, which will cause user interaction to be suspended as stated above. User A won't be able to submit his changes (which, by the way, would cause user B changes to be overwritten). In order to avoid this issue, a custom authorization control system should be implemented (see Usage note below).
Usage note:
  • OpenSpace doesn't implement a default authorization control system to prevent unauthorized map editing actions. Implementing the preferred method to allow a user initiate the editing process on the client-side is up to the developer. A possible high-level workflow could be:
    1. user clicks on a button to enter his own home (for example): a custom request is sent to the application' server-side extension (which in turn extends the default OpenSpace Extension);
    2. if this is the first time the user enters his home, on the server-side the extension generates a map file by duplicating a predefined template (the empty home) created by map designers with the OpenSpace Editor;
    3. a SmartFoxServer Room is created (with the user set as its owner) and the map is assigned to him by means of Room Variables (check the loadMap method for more informations on map-Room association);
    4. by means of the OpenSpaceExtension.sendAvatarToMap method, the user is joined to the newly created Room and the map data is sent to the OpenSpace client;
    5. on the client-side, the user clicks on a button to start map editing;
    6. user submits the map changes to the server: by overriding the OpenSpaceExtension._isMapUpdateAllowed method in the server-side extension, an additional check should be made to be sure that the user is the 'owner' of the Room: if yes, map updating is allowed.
Events broadcasted to listeners:
  • OpenSpaceEvent with type: EDIT_MODE_ENTERED
    • Dispatched when EDIT MODE is entered at runtime.
Example:
  • Enter EDIT MODE:
    openSpace.enterEditMode()

getAllSkinsByName

public function getAllSkinsByName (
name:String) : Array

Retrieve an array of skin display objects contained on the current map by means of their common instance name.
If an instance name is assigned to skin inside a tile during the tile creation in the OpenSpace Editor, and then that tile is added multiple times to the same map, it is possible to retrieve all the skin instances at once using this method (for examnple we could retrieve all the trees of a certain type).
Parameters:
name:
the name of the skin instance, assigned during the tile creation in the OpenSpace Editor.
Returns:
  • An array of flash.display.DisplayObjects representing the skins.
Example:
  • Get all the skins named 'oakTree' existing on the current map:
    var oakTrees:Array = openSpace.getAllSkinsByName("oakTree")
See also:

getAvatarById

public function getAvatarById (
avatarId:int) : Avatar

Get a reference to any user's main avatar.
Check the Avatar class description for more informations on "main" and "ghost" avatar distinction.
null is returned if currently the user's avatar is not on the map.
Parameters:
avatarId:
the avatar's identifier, corresponding to the SmartFoxServer id of the avatar's owner.
Example:
  • Retrieve a reference to the main avatar of a user and cast it to the proper child class:
    var demoAvatar:DemoAvatar = openSpace.getAvatarById(34) as DemoAvatar

getBackgroundParts

public function getBackgroundParts (
) : Array2

Retrieve an array of references to the display objects making up the background of the current map.
This method gives access to the background parts of the map, allowing runtime changes to the graphical assets.
Returns:
  • A de.polygonal.dsx
    .Array2
    object containing the background parts.
Example:
  • Get all the background parts of the current map:
    var bg:Array2 = openSpace.getBackgroundParts()

getForegroundParts

public function getForegroundParts (
) : Array2

Retrieve an array of references to the display objects making up the foreground of the current map.
This method gives access to the foreground parts of the map, allowing runtime changes to the graphical assets.
Returns:
  • A de.polygonal.dsx
    .Array2
    object containing the foreground parts.
Example:
  • Get all the foreground parts of the current map:
    var fg:Array2 = openSpace.getForegroundParts()

getGhostAvatarById

public function getGhostAvatarById (
avatarId:int) : Avatar

Get a reference to any user's ghost avatar.
Check the Avatar class description for more informations on "main" and "ghost" avatar distinction.
null is returned if the user's ghost avatar is not available.
Parameters:
avatarId:
the avatar's identifier, corresponding to the SmartFoxServer id of the avatar's owner.
Example:
  • Retrieve a reference to the ghost avatar of a user and cast it to the proper child class:
    var demoGhost:DemoGhost = openSpace.getGhostAvatarById(34) as DemoGhost
See also:

getGroup

public function getGroup (
groupId:String) : Array

Retrieve the list of Tile objects which are part of the specified group.
The id of a group of tiles is generated by the OpenSpace Editor when a supertile is dragged on the map. It is also returned by the Tile.groupId property.
Parameters:
groupId:
the id of the group, assigned during the map creation in the OpenSpace Editor.
Returns:
  • An array of Tile objects or null if the group doesn't exist on the current map.
Example:
  • Get the tiles belonging to group 'g3':
    var tiles:Array = openSpace.getGroup("g3")
See also:

getInventoryItemCount

public function getInventoryItemCount (
itemId:String) : int

Retrieve the number of instances of an inventory item placed on the current map.
This method can be useful to track the available inventory items quantities, for example to inhibit item drag&drop during map editing if the quantity is 0.
Parameters:
itemId:
the id of the inventory item to be counted (see the InventoryItem.id property).
Returns:
  • the number of instances of the requested inventory item placed on the current map; if no map is currently loaded, 0 is returned.
Example:
  • Check the example provided in the loadInventory method description (onOpenSpaceInventoryLoaded listener).

getInventoryItemSprite

public function getInventoryItemSprite (
itemId:String, itemDir:int) : Sprite

Retrieve the graphics of an inventory item.
This method can be used to display the available inventory items in a separate component in the main application interface (for example a list, or a datagrid).
As each inventory item can have multiple views (corresponding to different rotation angles - see the InventoryItem.directions property), a direction must be passed to retrive the proper graphics.
NOTE: SWF file/s required by OpenSpace to render the inventory item graphics (see the OpenSpaceEvent.INVENTORY_LOADED event parameters) must be loaded in the same application domain containing the skins of the current map before this method can be used.
Parameters:
itemId :
the id of the inventory item whose graphics is requested (see the InventoryItem.id property).
itemDir:
the view direction to be retrieved (see the InventoryItem.directions property).
Returns:
  • a flash.display.Sprite object containing the requested inventory item graphics.
Example:
  • Check the example provided in the loadInventory method description: in the onOpenSpaceInventoryLoaded listener, required SWF files loading should be launched.
    On loading completion we can create a data provider containing the inventory items relevant properties and their graphical representation retrieved using the this method; we can then display the available inventory items in the application interface by assigning the data provider to a List or DataGrid component.

getMapSize

public function getMapSize (

Get the size of the current map.
Returns:
  • A MapSize object containing the map's base grid width and height values.
Example:
  • Trace the dimensions of the current map:
    var mapSize:MapSize = openSpace.getMapSize()
    
    trace("Current map is", mapSize.width, "x", mapSize.height, "tiles")

getMyAvatar

public function getMyAvatar (
) : Avatar

Get a reference to the player's main avatar.
Check the Avatar class description for more informations on "main" and "ghost" avatar distinction.
null is returned if currently the player's avatar is not on the map.
Example:
  • Retrieve a reference to the main avatar and cast it to the proper child class:
    var demoAvatar:DemoAvatar = openSpace.getMyAvatar() as DemoAvatar
See also:

getMyAvatarCurrentTile

public function getMyAvatarCurrentTile (
) : Tile

Get a reference to the tile on which the player's avatar is currently standing.
Returns:
  • A reference to the Tile object corresponding to the tile on which the player's avatar is currently standing.
Example:
  • Get the tile on which the player's avatar is placed:
    openSpace.getMyAvatarCurrentTile()
See also:

getMyGhostAvatar

public function getMyGhostAvatar (
) : Avatar

Get a reference to the player's ghost avatar.
Check the Avatar class description for more informations on "main" and "ghost" avatar distinction.
null is returned if the player's ghost avatar is not available.
Example:
  • Retrieve a reference to the ghost avatar and cast it to the proper child class:
    var demoGhost:DemoGhost = openSpace.getMyGhostAvatar() as DemoGhost
See also:

getSkinByName

public function getSkinByName (
tileName:String, skinName:String) : DisplayObject

Retrieve a skin display object contained in a specific Tile object on the current map by means of its instance name.
Parameters:
tileName:
the name of the tile instance, assigned during the map creation in the OpenSpace Editor.
skinName:
the name of the skin instance, assigned during the tile creation in the OpenSpace Editor.
Returns:
  • A reference to the flash.display.DisplayObject (can be a Sprite or a MovieClip) representing the skin.
Example:
  • Get the skin named 'door' inside the tile named 'house1_door':
    var doorSkin:Sprite = openSpace.getSkinByName("house1_door", "door") as Sprite

getTileByCoordinates

public function getTileByCoordinates (
coords:Position3D) : Tile

Retrieve a reference to a Tile object on current the map by means of its coordinates.
If passed coordinates are outside the map boundaries, a null value is returned.
Parameters:
coords:
a Position3D object containing the tile coordinates; if -1 is passed as pz coordinate, the top tile of the (px,py) stack is returned.
Returns:
  • A reference to a Tile object.
Example:
  • Get the (0,0) tile:
    var coords:Position3D = new Position3D(0,0)
    var tile:Tile = openSpace.getTileByCoordinates(coords)
See also:

getTileByName

public function getTileByName (
tileName:String) : Tile

Retrieve a reference to a Tile object on the current map by means of its instance name.
Parameters:
tileName:
the name of the tile instance, assigned during the map creation in the OpenSpace Editor.
Returns:
  • A reference to a Tile object.
Example:
  • Get the tile named 'house1_door', representing the tile containing the door of the 'house 1' building:
    var tile:Tile = openSpace.getTileByName("house1_door")

hideWireframe

public function hideWireframe (
) : void

Hide the structure of tiles on the current map.
This method overrides the default value set in the OpenSpace client-side configuration, but wireframe visibility is set back to it each time the loadMap method is called.
Example:
  • Hide the map wireframe and fill:
    openSpace.hideWireframe()
See also:

init

public function init (
smartFoxClient:*, customItemSelector:AbstractMapItemSelector = null) : void

Initialize OpenSpace.
When this method is called, OpenSpace performs the following actions:When calling this method all the required external OpenSpaceEvent, MapInteractionEvent and AvatarEvent event listeners should have already been added to OpenSpace.
This method can be called only once per application execution. After initialization, maps can be loaded using the loadMap method.
The customItemSelector parameter can be used to pass an instance of a class extending AbstractMapItemSelector. OpenSpace uses this class to display a custom item selection highlighter during map editing (see the class description for more informations). If null is passed, a default map item selector is used.
Parameters:
smartFoxClient :
a reference to the SmartFoxServer client API instance created in the main application.
customItemSelector:
a reference to an instance of a custom class extending AbstractMapItemSelector.
Events broadcasted to listeners:
  • OpenSpaceEvent with type: INITIALIZED
    • Dispatched when OpenSpace is initialized.
Throws:
  • MyUserIdNotSetException if the id of the player is not set in the SmartFoxServer client API (SmartFoxServer 1.x only).
Example:
  • Connect to SmartFoxServer 1.x and login, then initialize the OpenSpace instance:
    var smartFox:SmartFoxClient = new SmartFoxClient()
    
    // Connect
    smartFox.connect("127.0.0.1", 9339)
    smartFox.addEventListener(SFSEvent.onConnection, onSFSConnection)
    smartFox.addEventListener(SFSEvent.onRoomListUpdate, onSFSRoomListUpdate)
    
    // On connection, perform login
    function onSFSConnection(evt:SFSEvent):void
    {
        if (evt.params.success)
            smartFox.login(smartFox.defaultZone, "kitcarson", "")
    }
    
    // After login, when the room list is received, add some event listeners and initialize OpenSpace
    function onSFSRoomListUpdate(evt:SFSEvent):void
    {
        openSpace.addEventListener(OpenSpaceEvent.INITIALIZED, onOpenSpaceInitialized)
        openSpace.addEventListener(OpenSpaceEvent.RESET, onOpenSpaceReset)
        openSpace.addEventListener(OpenSpaceEvent.MAP_LOADED, onOpenSpaceMapLoaded)
        openSpace.addEventListener(OpenSpaceEvent.MAP_CREATION_PROGRESS, onOpenSpaceMapProgress)
        openSpace.addEventListener(OpenSpaceEvent.MAP_RENDERED, onOpenSpaceMapRendered)
        openSpace.addEventListener(OpenSpaceEvent.MAP_ERROR, onOpenSpaceMapError)
    
        openSpace.init(smartFox)
    }

  • Connect to SmartFoxServer 2X and login, then initialize the OpenSpace instance:
    var smartFox:SmartFox = new SmartFox()
    smartFox.addEventListener(SFSEvent.CONNECTION, onSFSConnection)
    smartFox.addEventListener(SFSEvent.LOGIN, onSFSLogin)
    
    // Connect
    smartFox.connect()
    
    // On connection, perform login
    function onSFSConnection(evt:SFSEvent):void
    {
        if (evt.params.success)
            smartFox.send(new LoginRequest("Bax", "", ""));
    }
    
    // After login add some event listeners and initialize OpenSpace
    function onSFSLogin(evt:SFSEvent):void
    {
        openSpace.addEventListener(OpenSpaceEvent.INITIALIZED, onOpenSpaceInitialized)
        openSpace.addEventListener(OpenSpaceEvent.RESET, onOpenSpaceReset)
        openSpace.addEventListener(OpenSpaceEvent.MAP_LOADED, onOpenSpaceMapLoaded)
        openSpace.addEventListener(OpenSpaceEvent.MAP_CREATION_PROGRESS, onOpenSpaceMapProgress)
        openSpace.addEventListener(OpenSpaceEvent.MAP_RENDERED, onOpenSpaceMapRendered)
        openSpace.addEventListener(OpenSpaceEvent.MAP_ERROR, onOpenSpaceMapError)
    
        openSpace.init(smartFox)
    }

leaveEditMode

public function leaveEditMode (
saveChanges:Boolean) : void

Leave EDIT MODE and go back to PLAY MODE.
When leaving EDIT MODE, map changes can be saved or discarded by means of the saveChanges parameter. The following use cases can occurr.
  • Map was updated and the player wants to save it: changes are sent to the OpenSpace Extension which validates them, updates the map and stores it; the OpenSpaceEvent.MAP_UPDATED event is then fired by the OpenSpace instance on the other clients connected to the same Room, while the user interaction is frozen until the map is reloaded (it is necessary to call again the loadMap method).
  • Map was updated but the player wants to discard the changes: no data is sent to the OpenSpace Extension (so no event is fired on the other clients); the player's client automatically reloads the current map to revert to the last saved version.
  • Map was not updated: even if true is passed to this method, no data is sent to the OpenSpace Extension, and no map reloading occurs on the clients.
In any case, when the EDIT MODE is left, the player's client recreates the avatars and enables the standard user interaction.

NOTE: if a large number of changes is made by the player during map editing, the data sent to the OpenSpace Extension upon saving may exceed the maximum message size accepted by SmartFoxServer. For this reason the SmartFoxServer's <MaxMsgLen> configuration parameter must be properly tuned after evaluating the reasonable message size during the normal usage of the runtime map editing feature.
Parameters:
saveChanges:
if true, map changes are sent to the OpenSpace Extension to be saved.
Events broadcasted to listeners:
  • OpenSpaceEvent with type: EDIT_MODE_LEFT
    • Dispatched when EDIT MODE is left at runtime.
  • OpenSpaceEvent with type: MAP_UPDATE_ERROR
    • Dispatched when an error occurs in the OpenSpace Extension while updating a map.
  • OpenSpaceEvent with type: MAP_UPDATED
    • Dispatched when the current map is updated by another user.
Example:
  • Leave EDIT MODE and save the map changes:
    openSpace.leaveEditMode(true)
See also:

loadInventory

public function loadInventory (
projectId:String = "", filterParams:Object = null) : void

Load an inventory.
An inventory is a collection of items defined in an OpenSpace Editor project which can be added to / removed from a map during runtime editing.
When this method is called, the inventory is requested to the OpenSpace Extension; when a response is received the OpenSpaceEvent.INVENTORY_LOADED event (if inventory was loaded successfully) or the OpenSpaceEvent.INVENTORY_ERROR event (if an error occurred during data loading/parsing) is fired.
After OpenSpace has been initialized, this method can load any inventory belonging to any OpenSpace Editor project by passing the project id as first parameter. If the id is not passed, the project id of the currently loaded map (if any) is used to request the inventory to the OpenSpace Extension.
When requesting an inventory to the OpenSpace Extension, an object containing custom filtering parameters can be passed (see the OpenSpaceExtension._getInventoryItemsList method description in the OpenSpace Extension API documentation for more informations).

IMPORTANT NOTE: during runtime map editing, an inventory item can be placed on a map if its project id matches the map project id only.
Parameters:
projectId :
the id of the OpenSpace Editor project to which the inventory to be loaded belongs (optional).
filterParams:
an object containing custom parameters to be sent to the OpenSpace Extension (valid types are strings, numbers, booleans, arrays and objects) for inventory items filtering purposes (optional).
Events broadcasted to listeners:
  • OpenSpaceEvent with type: INVENTORY_LOADED
    • Dispatched when the inventory data is returned by the OpenSpace Extension and it is parsed successfully.
  • OpenSpaceEvent with type: INVENTORY_ERROR
    • Dispatched when an error occurs while loading or parsing the inventory data.
Example:
  • Iterate through the inventory items returned by the OpenSpaceEvent.INVENTORY_LOADED event, set an additional "quantity" property on each item and trace its properties:
    // Handle an interface "edit" button click event
    function onEditButtonClick(evt:Event):void
    {
        // A listener to the INVENTORY_LOADED event has already been added, before the OpenSpace initialization,
        // and a map has already been loaded (otherwise we should provide a project id)
    
        // Enter OpenSpace EDIT mode
        openSpace.enterEditMode()
    
        // Load the inventory corresponding to the current map
        openSpace.loadInventory()
    }
    
    // Handle the INVENTORY_LOADED event
    function onOpenSpaceInventoryLoaded(evt:OpenSpaceEvent):void
    {
        // NOTE: when the inventory items are received,
        // the SWF files containing their graphical assets should be loaded
    
        // Trace inventory items properties
        var inventoryItems:Array = evt.params.items
    
        for (var i:int = 0; i < inventoryItems.length; i++)
        {
            var item:InventoryItem = inventoryItems[i]
    
            // Add the item quantity (InventoryItem class is dynamic)
            // NOTE: using the OpenSpace.getInventoryItemCount method we can subtract the number of instances
            // of the current item already on the map from a default quantity (10 in this case),
            // to obtain the "remaining" available quantity
            item.quantity = (10 - openSpace.getInventoryItemCount(item.id))
    
            // Trace all properties
            trace("Inventory item properties:")
            trace("\t id:", item.id)
            trace("\t type:", item.type)
            trace("\t directions:", item.directions)
            trace("\t OS Editor custom properties:")
            for (var p:String in item.custom)
                trace("\t\t" + p + " -> " + item.custom[p])
            trace("\t available quantity:", item.quantity)
        }
    }

loadMap

public function loadMap (
room:*, password:String = "") : void

Join a SmartFoxServer Room and load the corresponding map data.
In OpenSpace, each map is assigned to a SmartFoxServer Room object by means of the _os_mapId Room Variable, which must contain the map export name as defined in the OpenSpace Editor (excluding the .map file extension).
The process of joining the Room is in charge of the OpenSpace Extension: if the Room is joined successfully, map data is received, processed and the OpenSpaceEvent.MAP_LOADED event is fired. OpenSpace is then ready to render the map (see the renderMap method).
If Room can't be joined (for example its maximum capacity has been reached), or if an errer occurs during map data loading and processing, the OpenSpaceEvent.MAP_ERROR or OpenSpaceEvent.MAP_FAILURE events are fired.
This method can be called after OpenSpace has been initialized only (see init method).
Parameters:
room :
the name or id of the SmartFoxServer Room to be joined.
password:
the password of the SmartFoxServer Room to be joined, in case it is a private room.
Events broadcasted to listeners:
  • OpenSpaceEvent with type: MAP_LOADED
    • Dispatched when a map data file is loaded and parsed successfully.
  • OpenSpaceEvent with type: MAP_ERROR
    • Dispatched when a non-blocking error occurs while loading a map.
  • OpenSpaceEvent with type: MAP_FAILURE
    • Dispatched when a blocking error occurs while loading/parsing/rendering a map.
Example:
  • Load a map after the OpenSpace initialization completion:
    // Add initialization and map loaded listeners
    openSpace.addEventListener(OpenSpaceEvent.INITIALIZED, onOpenSpaceInitialized)
    openSpace.addEventListener(OpenSpaceEvent.INITIALIZED, onOpenSpaceMapLoaded)
    
    // Initialize OpenSpace
    openSpace.initialize(smartFox)
    
    // On OpenSpace initialization, load a map
    function onOpenSpaceInitialized(evt:OpenSpaceEvent):void
    {
        openSpace.loadMap("House1Outside")
    }
    
    // Handle the MAP_LOADED event
    function onOpenSpaceMapLoaded(evt:OpenSpaceEvent):void
    {
        // On map loading completion we can load skins and backgrounds libraries and launch map rendering
        // ...
    }
See also:

moveMyAvatar

public function moveMyAvatar (
coords:Position3D, disableUserInteraction:Boolean = false) : void

Make the player's avatar walk to a tile on the map.
This method can be used to send the avatar from the current tile (for example a sensor tile which has triggered an event) to another on the same map automatically, without the need of user interaction (e.g. mouse click on the destination tile).
This method behaves just like if the user clicked the destination tile using the mouse cursor; as a consequence, if during the automatic movement the user clicks on a different tile, a new destination will be set.
In order to force the avatar to reach the given target coordinates, the user interaction should be disabled by means of the disableUserInteraction parameter, and re-enabled when the movement ends by menas of the userInteractionEnabled property.
During the avatar movement, all the movement-related events are triggered as usual.
This action is broadcasted to all the users in the SmartFoxServer Room corresponding to the current map, so that the avatar will start moving on all the clients.
Parameters:
coords :
a Position3D object containing the target tile coordinates; if -1 is passed as pz coordinate, the top tile of the (px,py) stack is used.
disableUserInteraction:
if true is passed, user interaction is disabled before starting the avatar movement (optional).
Events broadcasted to listeners:
  • AvatarEvent with type: START_MOVEMENT
    • Dispatched when an avatar standing on a tile starts moving.
  • AvatarEvent with type: STOP_MOVEMENT
    • Dispatched when a moving avatar stops on a tile.
  • AvatarEvent with type: ENTER_TILE
    • Dispatched when an avatar enters a tile during its movement.
  • AvatarEvent with type: LEAVE_TILE
    • Dispatched when an avatar leaves a tile during its movement.
Throws:
Example:
  • Move the player's avatar to (12,7) coordinates disabling the user interaction:
    // Set destination coordinates
    var coords:Position3D = new Position3D(12,7)
    
    // Move avatar
    openSpace.moveMyAvatar(coords, true)

panView

public function panView (
dx:int, dy:int, overrideLimits:Boolean = false, showAnimation:Boolean = true) : void

Pan the viewport.
Shift the viewport to reveal another portion of the map, without the need to make an avatar walk around, causing the map to scroll.
This method is available whether the player's avatar has been created or not.
Parameters:
dx :
the viewport shift distance along the x axis in the stage coordinates system.
dy :
the viewport shift distance along the y axis in the stage coordinates system..
overrideLimits:
if true, viewport is shifted regardless if the final position exceeds the map boundaries, showing a blank portion of the map.
showAnimation :
if true, a scrolling animation from the current viewport position to the final position is shown; if false, the viewport is shifted immediately. In both cases, the relevant camera parameters from the OpenSpace client-side configuration are applied.
Usage note:
  • Implementing this function can be useful to make guest users explore the virtual world without allowing map interaction.
    Another possible usage is map navigation during runtime editing.
Events broadcasted to listeners:
  • OpenSpaceEvent with type: ANIMATION_START
    • Dispatched when the map animation (pan/zoom/scroll) starts.
  • OpenSpaceEvent with type: ANIMATION_END
    • Dispatched when the map animation (pan/zoom/scroll) ends.
Example:
  • Pan viewport horizontally for a distance of 100 pixels:
    openSpace.panView(100, 0)
See also:

removeMyAvatar

public function removeMyAvatar (
) : void

Remove the player's avatar.
This method removes the avatar of the player from the map, therefore disabling the player interaction with the map (while he is still able to explore it using the pan and zoom features - see panView and zoomView methods).
This action is broadcasted to all the users in the SmartFoxServer Room corresponding to the current map, so that the avatar can be removed on all the clients.
An avatar can be recreated after being removed by means of the createMyAvatar method.
Throws:
Example:
  • Remove the player's avatar from the map:
    openSpace.removeMyAvatar(params)
See also:

renderMap

public function renderMap (
params:MapCenteringParams = null) : void

Render a loaded map.
The map rendering process requires skins and background parts classes definitions to be available in the skinAppDomain and bgAppDomain application domains respectively.
Also, as avatars of users already on the map are created at the end of the rendering, just before the map is displayed, all avatar classes definitions must be available in the avatarAppDomain application domain.
If one or more external SWF files are used as libraries, these should be loaded before launching the map rendering process.
During rendering, the OpenSpaceEvent.MAP_CREATION_PROGRESS event is fired, returning the map creation percentage.
At the end of tiles rendering, avatars are created and the map is displayed in the viewport with a fade-in transition (according to the client-side configuration settings). The OpenSpaceEvent.MAP_RENDERED event is also fired.
Parameters:
params:
a collection of optional parameters to control the map centering in the viewport.
Events broadcasted to listeners:
  • OpenSpaceEvent with type: MAP_CREATION_PROGRESS
    • Dispatched when a progress occurs during the tiles instances creation process.
  • OpenSpaceEvent with type: MAP_RENDERED
    • Dispatched when the tiles instances creation process is completed and the isometric environment described by the loaded map has been rendered on the stage.
  • OpenSpaceEvent with type: MAP_FAILURE
    • Dispatched when a blocking error occurs while loading/parsing/rendering a map.
Example:
  • On map loading completion, load skins and backgrounds library and launch map rendering:
    // We need a new application domain where to store skins and background parts classes definitions
    var swfLibrariesAppDomain:ApplicationDomain = new ApplicationDomain()
    
    // Connection to SmartFoxServer is established, OpenSpace is initialized and a map is loaded
    // ...
    
    // Handle the MAP_LOADED event
    function onOpenSpaceMapLoaded(evt:OpenSpaceEvent):void
    {
        // We just have one external library file for both skins and background parts
        var fileName:String = evt.params.skinSwfFiles[0]
    
        var loader:Loader = new Loader()
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onMapSwfFileLoaded)
    
        var request:URLRequest = new URLRequest("libraries/" + fileName)
        var context:LoaderContext = new LoaderContext(false, swfLibrariesAppDomain)
    
        loader.load(request, context)
    }
    
    // Handle external SWF file loading completion
    function onMapSwfFileLoaded(evt:Event):void
    {
        // The same value is passed to both skinAppDomain and bgAppDomain parameters
        // as we are using one common application domain only
        openSpace.skinAppDomain = swfLibrariesAppDomain
        openSpace.bgAppDomain = swfLibrariesAppDomain
    
        // Render map
        openSpace.renderMap()
    }
    
    // Handle the MAP_CREATION_PROGRESS event
    function onOpenSpaceMapProgress(evt:OpenSpaceEvent):void
    {
        trace("Map generation progress: " + evt.params.percentage + "%")
    }
    
    // Handle the MAP_RENDERED event
    function onOpenSpaceMapRendered(evt:OpenSpaceEvent):void
    {
        // Create player's avatar
        // ...
    }
    NOTE: for sake of simplicity, in the above example both skins and background parts are supposed to be contained in the same SWF file, which is loaded in a common application domain.
    A number of improvements should be made:
    1. skins and background parts should be contained in separate SWF files, which should be loaded in separate application domains in order to avoid possible conflicts if the class definitions they contain have the same names;
    2. in case the loaded map shares the same SWF files of the previous map, reloading is unnecessary and should be avoided not to waste memory;
    3. if SWF files for the previous map are not needed anymore, they should be unloaded.

setCustomMapLimits

public function setCustomMapLimits (
limits:Rectangle) : void

Set the limits of the current map.
Custom map limits can be defined at runtime by means of a rectangle acting as a virtual map boundary to limit the camera movements during panning, zooming or viewport scrolling caused by the avatar movement.
If null is passed, limits are set back to the default values defined inside the OpenSpace Editor.

NOTE: the rectangle x,y origin is measured with respect to the map grid (0,0) coordinates, as shown in the following picture:
Parameters:
limits:
a flash.geom.Rectangle object defining the map boundaries origin, width and height.
Example:
  • Limit the right panning in a 640x480 pixels viewport, setting the virtual right limit at a distance of 100 pixels from the true right boundary of the map:
    var mapLimits:Rectangle = new Recteangle(0,0, 540, 480)
    openSpace.setCustomMapLimits(mapLimits)

setMyAvatarAction

public function setMyAvatarAction (
action:Object) : void

Make the player's avatar perform a custom action.
This method takes effect only if the Avatar.onCustomAction method has been overridden in the custom child avatar class. See the property description for more informations.
This action is broadcasted to all the users in the SmartFoxServer Room corresponding to the current map, so that the avatar action can be displayed by all the clients.
Parameters:
action:
an Object containing any number of custom parameters describing the action to perform (valid types are strings, numbers, booleans, arrays and objects).
Throws:
Example:
  • Make the player's avatar applaude:
    // Crete action object
    var avatarAction:Object = {}
    avatarAction.id = "applaude"
    
    // Perform action
    openSpace.setMyAvatarAction(avatarAction)

setMyAvatarAnimationTime

public function setMyAvatarAnimationTime (
animationTime:int) : void

Change the duration of the player's avatar movement from tile to tile along N/E/S/W directions.
This method is used to alter the duration of the animation (in other words the speed) when the avatar moves from one tile to the next one along the diagonal directions. The initial duration can be set by means of the AvatarCreationParams.animationTime parameter.
The animation duration is expressed in milliseconds. A correction is applied for the other directions, to make the avatar have the same speed when moving in any direction.
In order to set the movement duration back to the default AvatarDefaults.ANIMATION_TIME value, -1 should be passed to this method.
Parameters:
animationTime:
the duration in milliseconds of the avatar movement.
Throws:
Example:
  • Make the player's avatar move faster by setting a low movement duration value:
    openSpace.setMyAvatarAnimationTime(150)

setMyAvatarSkin

public function setMyAvatarSkin (
skin:Object) : void

Set the skin of the player's avatar.
This method takes effect only if the Avatar.skin property has been overridden in the custom child avatar class. See the property description for more informations.
This action is broadcasted to all the users in the SmartFoxServer Room corresponding to the current map, so that the avatar skin can be changed on all the clients.
Parameters:
skin:
an Object containing any number of custom parameters describing the avatar's skin (valid types are strings, numbers, booleans, arrays and objects).
Throws:
Example:
  • Set the skin of the player's avatar:
    // Crete new skin object
    var avatarSkin:Object = {}
    avatarSkin.sex = "m"
    avatarSkin.hat = "indianFeather"
    
    // Set new skin
    openSpace.setMyAvatarSkin(avatarSkin)
See also:

setMyAvatarState

public function setMyAvatarState (
state:Object) : void

Change the state of the player's avatar.
This method takes effect only if the Avatar.state method has been overridden in the custom child avatar class. See the property description for more informations.
This action is broadcasted to all the users in the SmartFoxServer Room corresponding to the current map, so that the avatar state can be displayed by all the clients.
Parameters:
state:
an Object containing any number of custom parameters describing the avatar state (valid types are strings, numbers, booleans, arrays and objects).
Throws:
Example:
  • Make the player's avatar sit:
    // Crete action object
    var avatarState:Object = {}
    avatarState.id = "sit"
    
    // Change state
    openSpace.setMyAvatarState(avatarState)
See also:

showWireframe

public function showWireframe (
showFill:Boolean = false) : void

Show the structure of tiles on the current map.
Useful for debugging purposes, to check the map morphology regardless of the tile skins and the map background.
This method overrides the default value set in the OpenSpace client-side configuration, but wireframe visibility is set back to it each time the loadMap method is called.
Parameters:
showFill:
colour the faces of tile blocks, delimited by the wireframe borders (optional).
Example:
  • Show the map wireframe and fill:
    openSpace.showWireframe(true)
See also:

stopAvatarLocal

public function stopAvatarLocal (
avatarId:int) : void

Stop a moving avatar on the current client only.
This method can be used to stop an avatar immediately, for example if a user stepped on a forbidden tile (which triggered an AvatarEvent.ENTER_TILE event) and we want to freeze it.
This action is executed locally only, without being automatically broadcasted to the other clients connected to the same SmartFoxServer Room. For this reason this method should be called on all the clients as a consequence of a custom extension message coming from the server.
When the avatar movement is stopped using this method, it can't be resumed: the avatar should be recreated by means of the createMyAvatar method.
NOTE: if the viewport is currently scrolling, OpenSpace ignores the stop request.
Parameters:
avatarId:
the avatar's identifier, corresponding to the SmartFoxServer id of the avatar's owner.
Example:
  • Stop a user avatar as a consequence of an incoming custom extension response containing the id of the avatar to be stopped:
    function onExtensionResponse(evt:SFSEvent):void
    {
        var type:String = evt.params.type
        var evtData:Object = evt.params.dataObj
    
        var cmd:String = evtData._cmd
    
        if (cmd == "stopAvatar")
        {
            var avatarId:int = evtData.id
    
            // Stop the avatar
            openSpace.stopAvatarLocal(avatarId)
        }
    }
See also:

stopMyAvatar

public function stopMyAvatar (
) : void

Stop the player's avatar while moving.
This method can be used to stop the avatar on a tile (for example a sensor tile which triggers the AvatarEvent.ENTER_TILE event, informing the application that the avatar stepped on that tile).
The avatar always stops in the center of the tile it is currently moving on, unless it already passed that point: in this case it will stop in the center of the next tile of the path (see next image).

In order to make the avatar stop immediately, without waiting it to reach the center of the current or next tile, a different approach must be followed, which involves the stopAvatarLocal method.
When the avatar movement is stopped, it can be resumed by means of a player's click on a tile or by calling the moveMyAvatar method.
This action is broadcasted to all the users in the SmartFoxServer Room corresponding to the current map, so that the avatar will stop on all the clients.
NOTE: if the viewport is currently scrolling, OpenSpace ignores the stop request.
Events broadcasted to listeners:
  • AvatarEvent with type: STOP_MOVEMENT
    • Dispatched when a moving avatar stops on a tile.
Throws:
Example:
  • Stop the player's avatar:
    openSpace.stopMyAvatar()

teleportMyAvatar

public function teleportMyAvatar (
coords:Position3D, direction:int = -1, applyHeightCorrection:Boolean = true, showEffect:Boolean = true) : void

Make the player's avatar appear on a new tile on the map instantly.
This method can be used to "teleport" the avatar from the current tile (for example a sensor tile which has triggered an event) to another on the same map, at any distance.
This action is broadcasted to all the users in the SmartFoxServer Room corresponding to the current map, so that the avatar will be teleported on all the clients.
NOTE: if the viewport is currently scrolling, OpenSpace ignores the teleport request.
Parameters:
coords :
a Position3D object containing the target tile coordinates; if -1 is passed as pz coordinate, the top tile of the (px,py) stack is used.
direction :
the direction that the avatar should face when appearing on the new tile (valid values are contained in the AvatarDirections class); if -1 is passed, the current avatar direction is used.
applyHeightCorrection:
if false, upon teleporting completion the viewport is centered on the target tile (in other words at the avatar's feet); if true, the avatar's movieclip height is taken into account in order to center the avatar in the viewport properly.
showEffect :
if true, a fading transition effect is displayed during the teleporting; the effect parameters can be set in the OpenSpace client-side configuration.
Throws:
  • AvatarNotAvailableException if currently the player's avatar is not on the map.
  • InvalidMapCoordinatesException if the destination coordinates are invalid, or the avatar already stands on the target tile. This exception may also be thrown in case a generic error occurs during the teleport: we can check the client-side warnings to exactly understand the cause of the problem.
Example:
  • Teleport the player's avatar to (12,7) coordinates:
    // Set destination coordinates
    var coords:Position3D = new Position3D(12,7)
    
    // Teleport avatar
    openSpace.teleportMyAvatar(coords)

unloadMap

public function unloadMap (
) : void

Unload current map.
When this method is called, all map data structures are disposed and OpenSpace viewport is cleared showing a fade-out transition (according to the client-side configuration settings). The OpenSpaceEvent.RESET event is also fired.
This method can be used to stop (also temporarly) OpenSpace and avoid wasting CPU and memory while the user is not interacting with the isometric environment (for example the user is playing a game). To re-enable OpenSpace, simply load a new (or the same) map using the loadMap method.
This method is also called automatically when a blocking error occurs during map loading, parsing or rendering (see OpenSpaceEvent.MAP_FAILURE event).
Events broadcasted to listeners:
Example:
  • Clear OpenSpace viewport:
    openSpace.unloadMap()
See also:

zoomOnMyAvatar

public function zoomOnMyAvatar (
factor:Number, applyHeightCorrection:Boolean = true, showAnimation:Boolean = true) : void

Zoom the viewport on the player's avatar.
When zooming the viewport, map boundaries are taken into account to avoid showing a blank portion of the map (unless the viewport becomes bigger than the map during the zoom-out).
OpenSpace ignores this action if the player's avatar is not on the map.
Parameters:
factor :
the zoom factor; must be greater than 0; a value of 1 corresponds to the original map size (100% scaling).
applyHeightCorrection:
if false, viewport is centered on avatar's tile (in other words at the avatar's feet); if true, the avatar's movieclip height is taken into account in order to center the avatar in the viewport properly.
showAnimation :
if true, a zoom animation from the current map scaling factor to the final scaling factor is shown; if false, the map is resized immediately. In both cases, the relevant camera parameters from the OpenSpace client-side configuration are applied.
Events broadcasted to listeners:
  • OpenSpaceEvent with type: ANIMATION_START
    • Dispatched when the map animation (pan/zoom/scroll) starts.
  • OpenSpaceEvent with type: ANIMATION_END
    • Dispatched when the map animation (pan/zoom/scroll) ends.
Example:
  • Zoom-in the viewport on the player's avatar resizing the map to 200%:
    openSpace.zoomOnMyAvatar(2)

zoomView

public function zoomView (
factor:Number, showAnimation:Boolean = true, mapCenteringParams:MapCenteringParams = null) : void

Zoom the viewport.
Zoom-in or zoom-out the map passing the target scaling factor.
This method is available whether the player's avatar has been created or not. For example, this method can be used to make guest users explore the virtual world without allowing interaction.
Parameters:
factor :
the zoom factor; must be greater than 0; a value of 1 corresponds to the original map size (100% scaling).
showAnimation :
if true, a zoom animation from the current map scaling factor to the final scaling factor is shown; if false, the map is resized immediately. In both cases, the relevant camera parameters from the OpenSpace client-side configuration are applied.
mapCenteringParams:
an object containing the map coordinates to be centered during the zoom.
Events broadcasted to listeners:
  • OpenSpaceEvent with type: ANIMATION_START
    • Dispatched when the map animation (pan/zoom/scroll) starts.
  • OpenSpaceEvent with type: ANIMATION_END
    • Dispatched when the map animation (pan/zoom/scroll) ends.
Example:
  • Zoom-in viewport resizing the map to 200%:
    openSpace.zoomView(2)
See also: