diff --git a/CNAME b/CNAME
deleted file mode 100644
index f73928a..0000000
--- a/CNAME
+++ /dev/null
@@ -1 +0,0 @@
-docs.opensurge2d.org
\ No newline at end of file
diff --git a/engine/event/index.html b/engine/event/index.html
index d6a0cc7..5e19e15 100644
--- a/engine/event/index.html
+++ b/engine/event/index.html
@@ -1807,7 +1807,7 @@
Event
-An event is a function object that is tagged "event". Events are used to run code when triggered.
+An event is a function object with zero parameters and no return value that is tagged "event". Events are used to run code when triggered.
Events let you seamlessly connect entities and write cause and effect relationships. Suppose you have an on/off switch in a level. Whenever that switch is pressed by the player, you want something to happen: raise the water level, open a door, make it rain, teleport the player, and so on. Events are important because they let you decouple the source of the happening (the pressing of the switch) from the results that are experienced (e.g., the raising of the water).
Events let you reuse your entities in multiple ways and for multiple purposes. You may design an entity and make it trigger an event, but you do not need to specify in advance what the event actually is. Rather, the concrete event (what must happen) will be configured in your level setup.
There are multiple types of events. In practice, you'll use specialized events such as EntityEvent and FunctionEvent when configuring your entities. Event is an empty event that does nothing when triggered, but it should be used when designing your entities, as in the example below.
@@ -1865,7 +1865,7 @@ Events.Event
Functions
call
call()
-Triggers the event. All event types implement this function.
+Triggers the event. All event types implement this function. It takes no arguments and it returns no value other than null
.
diff --git a/js/analytics.js b/js/analytics.js
index d32380e..5a85be7 100644
--- a/js/analytics.js
+++ b/js/analytics.js
@@ -1,4 +1,4 @@
-window.addEventListener('load', function() {
+(function() {
const script = document.createElement('script');
script.addEventListener('error', function(e) {
@@ -11,4 +11,4 @@ window.addEventListener('load', function() {
script.src = 'https://gc.zgo.at/count.js';
document.head.appendChild(script);
-});
+})();
diff --git a/search/search_index.json b/search/search_index.json
index 1eb385b..eab5710 100644
--- a/search/search_index.json
+++ b/search/search_index.json
@@ -1 +1 @@
-{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Welcome to SurgeScript! Unleash your creativity! SurgeScript is a scripting language for games. Use it to unleash your creativity and build your own amazing interactive content! It's such a joy to use SurgeScript! You will love it! GET STARTED How do I learn SurgeScript? Check out the SurgeScript Crash Course ! Additionally, take a look at the video tutorials and at the examples that come with the software. SurgeScript in a nutshell SurgeScript is: A scripting language for games Easy for beginners, powerful for experts Object-oriented, dynamically typed and based on state machines Free and open-source software Built in C, which is nearly universal Named after a really charismatic character: Surge the Rabbit ! Why use SurgeScript? Unlike other programming languages, SurgeScript has been designed with the specific needs of games in mind. Its features include: The state-machine pattern: objects are state machines, making it easy to create game entities The composition approach: you may design complex objects and behaviors by means of composition The hierarchy system: objects have a parent and may have children, in a tree-like structure The game loop: it's defined implicitly Automatic garbage collection, object tagging and more! SurgeScript is meant to be used in games and in interactive applications. It's easy to integrate it into existing code, it's easy to extend it, it features a C-like syntax, and it's free and open-source software. SurgeScript has been designed based on the experience of its developer dealing with game engines, applications related to computer graphics and so on. Some of the best practices have been incorporated into the language itself, making things really easy for developers and modders. Who created SurgeScript? SurgeScript has been created by Alexandre Martins , a computer scientist from Brazil. He has also created the Open Surge game engine , hence the name SurgeScript.","title":"Introduction"},{"location":"#welcome-to-surgescript","text":"","title":"Welcome to SurgeScript!"},{"location":"#unleash-your-creativity","text":"SurgeScript is a scripting language for games. Use it to unleash your creativity and build your own amazing interactive content! It's such a joy to use SurgeScript! You will love it! GET STARTED","title":"Unleash your creativity!"},{"location":"#how-do-i-learn-surgescript","text":"Check out the SurgeScript Crash Course ! Additionally, take a look at the video tutorials and at the examples that come with the software.","title":"How do I learn SurgeScript?"},{"location":"#surgescript-in-a-nutshell","text":"SurgeScript is: A scripting language for games Easy for beginners, powerful for experts Object-oriented, dynamically typed and based on state machines Free and open-source software Built in C, which is nearly universal Named after a really charismatic character: Surge the Rabbit !","title":"SurgeScript in a nutshell"},{"location":"#why-use-surgescript","text":"Unlike other programming languages, SurgeScript has been designed with the specific needs of games in mind. Its features include: The state-machine pattern: objects are state machines, making it easy to create game entities The composition approach: you may design complex objects and behaviors by means of composition The hierarchy system: objects have a parent and may have children, in a tree-like structure The game loop: it's defined implicitly Automatic garbage collection, object tagging and more! SurgeScript is meant to be used in games and in interactive applications. It's easy to integrate it into existing code, it's easy to extend it, it features a C-like syntax, and it's free and open-source software. SurgeScript has been designed based on the experience of its developer dealing with game engines, applications related to computer graphics and so on. Some of the best practices have been incorporated into the language itself, making things really easy for developers and modders.","title":"Why use SurgeScript?"},{"location":"#who-created-surgescript","text":"SurgeScript has been created by Alexandre Martins , a computer scientist from Brazil. He has also created the Open Surge game engine , hence the name SurgeScript.","title":"Who created SurgeScript?"},{"location":"download/","text":"Download SurgeScript There are two ways to get SurgeScript: The first is to get Open Surge . This is recommended for most users. The second is to get the standalone version of the language. Open Surge To get Open Surge, visit opensurge2d.org and follow the instructions there. When you get Open Surge, you also get a full game engine featuring SurgeScript. This allows you to create your own scripts and games with plenty of interactivity and ease. Once you download Open Surge, the next step is to create your first script . Standalone version To get the standalone version, go to the SurgeScript page on GitHub . There you'll find instructions on how to compile SurgeScript. When you compile SurgeScript, you'll end up with a text-only program. There are no graphics and no game engine is attached to it. You can try your scripts using the command line. Once you get the standalone version, the next step is to create your first script .","title":"Download"},{"location":"download/#download-surgescript","text":"There are two ways to get SurgeScript: The first is to get Open Surge . This is recommended for most users. The second is to get the standalone version of the language.","title":"Download SurgeScript"},{"location":"download/#open-surge","text":"To get Open Surge, visit opensurge2d.org and follow the instructions there. When you get Open Surge, you also get a full game engine featuring SurgeScript. This allows you to create your own scripts and games with plenty of interactivity and ease. Once you download Open Surge, the next step is to create your first script .","title":"Open Surge"},{"location":"download/#standalone-version","text":"To get the standalone version, go to the SurgeScript page on GitHub . There you'll find instructions on how to compile SurgeScript. When you compile SurgeScript, you'll end up with a text-only program. There are no graphics and no game engine is attached to it. You can try your scripts using the command line. Once you get the standalone version, the next step is to create your first script .","title":"Standalone version"},{"location":"engine/actor/","text":"Actor The Actor component is used to associate a sprite to a target object. The target object is required to be an entity . It's recommended to use only one actor per entity. Factory Actor Actor(sprite) Spawns a new Actor component with the given sprite name. Arguments sprite : string. The name of the sprite (defined in the sprites/ folder). Returns An Actor component. Example using SurgeEngine.Actor ; object \"SurgeTest\" is \"entity\" { // spawns an Actor with the SurgeTest sprite actor = Actor ( \"SurgeTest\" ); state \"main\" { } } Properties anim anim : number. A shortcut to animation.id : an integer corresponding to the animation number. Defaults to 0. animation animation : Animation object, read-only. Reference to the Animation object of the Actor. entity entity : object, read-only. The entity associated with this component. hflip hflip : boolean. Should the actor be flipped horizontally? Defaults to false . vflip vflip : boolean. Should the actor be flipped vertically? Defaults to false . visible visible : boolean. Should the actor be rendered? Defaults to true . alpha alpha : number. Opacity value, ranging from zero (0% opaque) to one (100% opaque). Defaults to 1.0. offset offset : Vector2 object. A (x,y) offset relative to the parent object. Defaults to zero. anchor anchor : Vector2 object. A shortcut to animation.anchor . See also: anchor . Available since: Open Surge 0.6.0 hotSpot hotSpot : Vector2 object. A shortcut to animation.hotSpot . See also: hot spot . Available since: Open Surge 0.6.0. In versions prior to 0.6.0, you may get the hot spot using the Animation object. actionSpot actionSpot : Vector2 object. A shortcut to animation.actionSpot . See also: action spot . Available since: Open Surge 0.6.0 actionOffset actionOffset : Vector2 object, read-only. A shortcut to animation.actionOffset . See also: action offset . Available since: Open Surge 0.6.0 width width : number, read-only. The width of the actor. height height : number, read-only. The height of the actor. zindex zindex : number. Objects with greater zindex are rendered in front of others. Defaults to 0.5.","title":"Actor"},{"location":"engine/actor/#actor","text":"The Actor component is used to associate a sprite to a target object. The target object is required to be an entity . It's recommended to use only one actor per entity.","title":"Actor"},{"location":"engine/actor/#factory","text":"","title":"Factory"},{"location":"engine/actor/#actor_1","text":"Actor(sprite) Spawns a new Actor component with the given sprite name. Arguments sprite : string. The name of the sprite (defined in the sprites/ folder). Returns An Actor component. Example using SurgeEngine.Actor ; object \"SurgeTest\" is \"entity\" { // spawns an Actor with the SurgeTest sprite actor = Actor ( \"SurgeTest\" ); state \"main\" { } }","title":"Actor"},{"location":"engine/actor/#properties","text":"","title":"Properties"},{"location":"engine/actor/#anim","text":"anim : number. A shortcut to animation.id : an integer corresponding to the animation number. Defaults to 0.","title":"anim"},{"location":"engine/actor/#animation","text":"animation : Animation object, read-only. Reference to the Animation object of the Actor.","title":"animation"},{"location":"engine/actor/#entity","text":"entity : object, read-only. The entity associated with this component.","title":"entity"},{"location":"engine/actor/#hflip","text":"hflip : boolean. Should the actor be flipped horizontally? Defaults to false .","title":"hflip"},{"location":"engine/actor/#vflip","text":"vflip : boolean. Should the actor be flipped vertically? Defaults to false .","title":"vflip"},{"location":"engine/actor/#visible","text":"visible : boolean. Should the actor be rendered? Defaults to true .","title":"visible"},{"location":"engine/actor/#alpha","text":"alpha : number. Opacity value, ranging from zero (0% opaque) to one (100% opaque). Defaults to 1.0.","title":"alpha"},{"location":"engine/actor/#offset","text":"offset : Vector2 object. A (x,y) offset relative to the parent object. Defaults to zero.","title":"offset"},{"location":"engine/actor/#anchor","text":"anchor : Vector2 object. A shortcut to animation.anchor . See also: anchor . Available since: Open Surge 0.6.0","title":"anchor"},{"location":"engine/actor/#hotspot","text":"hotSpot : Vector2 object. A shortcut to animation.hotSpot . See also: hot spot . Available since: Open Surge 0.6.0. In versions prior to 0.6.0, you may get the hot spot using the Animation object.","title":"hotSpot"},{"location":"engine/actor/#actionspot","text":"actionSpot : Vector2 object. A shortcut to animation.actionSpot . See also: action spot . Available since: Open Surge 0.6.0","title":"actionSpot"},{"location":"engine/actor/#actionoffset","text":"actionOffset : Vector2 object, read-only. A shortcut to animation.actionOffset . See also: action offset . Available since: Open Surge 0.6.0","title":"actionOffset"},{"location":"engine/actor/#width","text":"width : number, read-only. The width of the actor.","title":"width"},{"location":"engine/actor/#height","text":"height : number, read-only. The height of the actor.","title":"height"},{"location":"engine/actor/#zindex","text":"zindex : number. Objects with greater zindex are rendered in front of others. Defaults to 0.5.","title":"zindex"},{"location":"engine/androidplatform/","text":"AndroidPlatform Routines specific to Android. The functions below do nothing if the engine is not running on it. In order to determine if the engine is running on Android, check Platform.isAndroid . Available since: Open Surge 0.6.1 Functions shareText shareText(text) Share a text using the Android Sharesheet, a feature that lets the user pick which app to share data with. You may use it to let the user share a URL with a friend or on social media, for example. Arguments text : string. The text to be shared. Example using SurgeEngine.Platform ; using SurgeEngine.Platform.Android ; // ... if ( Platform . isAndroid ) Android . shareText ( \"Download the Open Surge Engine at https://opensurge2d.org\" );","title":"Android"},{"location":"engine/androidplatform/#androidplatform","text":"Routines specific to Android. The functions below do nothing if the engine is not running on it. In order to determine if the engine is running on Android, check Platform.isAndroid . Available since: Open Surge 0.6.1","title":"AndroidPlatform"},{"location":"engine/androidplatform/#functions","text":"","title":"Functions"},{"location":"engine/androidplatform/#sharetext","text":"shareText(text) Share a text using the Android Sharesheet, a feature that lets the user pick which app to share data with. You may use it to let the user share a URL with a friend or on social media, for example. Arguments text : string. The text to be shared. Example using SurgeEngine.Platform ; using SurgeEngine.Platform.Android ; // ... if ( Platform . isAndroid ) Android . shareText ( \"Download the Open Surge Engine at https://opensurge2d.org\" );","title":"shareText"},{"location":"engine/animation/","text":"Animation Animation objects are used to gather data about specific animations. Although you can't spawn Animation objects directly, you can access them via other objects such as Actor and Player . Example using SurgeEngine.Actor ; object \"MyExplosion\" is \"entity\" , \"disposable\" , \"private\" { actor = Actor ( \"MyExplosion\" ); state \"main\" { if ( actor . animation . finished ) destroy (); } } Properties id id : number. The number of the animation, defined in a .spr file. sprite sprite : string, read-only. The name of the sprite, defined in a .spr file. exists exists : boolean, read-only. Will be true if the animation exists, i.e., if its sprite and its animation number have been defined in a .spr file. Available since: Open Surge 0.5.1 finished finished : boolean, read-only. Will be true if the animation has finished playing. anchor anchor : Vector2 object, read-only. The hot spot of the animation normalized to [0,1] x [0,1]. Available since: Open Surge 0.6.0 hotSpot hotSpot : Vector2 object, read-only. The hot spot of the animation. Coordinates are given in pixels. Note: prior to Open Surge 0.6.0, this property was called hotspot . actionSpot actionSpot : Vector2 object, read-only. The action spot of the animation. Coordinates are given in pixels. If the sprite is flipped, the action spot is automatically flipped relative to the hot spot of the animation. Available since: Open Surge 0.6.0 actionOffset actionOffset : Vector2 object, read-only. When this vector is added to the position of the sprite, you'll get the position of the action spot . This is suitable to be used with transform.localPosition . Available since: Open Surge 0.6.0 repeats repeats : boolean, read-only. Does the animation repeat itself? fps fps : number, read-only. Frames per second of the animation. frameCount frameCount : number, read-only. The number of frames of the animation. duration duration : number, read-only. The duration of the animation, in seconds. Available since: Open Surge 0.6.1 frame frame : number. The current frame of the animation: an integer between 0 and frameCount - 1 , inclusive. speedFactor speedFactor : number. While the FPS rate controls the speed of the animation, the speed factor gives you an additional degree of control. This is a multiplier that defaults to 1.0, meaning that the animation will run using its normal speed. If it's set to 2.0, it will run using twice that speed. A value of 0.5 means half the speed, and so on. sync sync : boolean. Is the animation is synchronized? A synchronized animation is a repeating animation that displays the same frame across multiple sprites. Defaults to false . Functions prop prop(propertyName) Read the user-defined custom property named propertyName defined in a custom_properties block of the sprite of this animation (.spr file). If the property exists, this function will return a string, a number, a boolean, or an Array of these, depending on the property. If the property does not exist, this function will return null . Available since: Open Surge 0.6.1 Arguments propertyName : string. The name of a custom property. Returns Returns a string, a number, a boolean, an array of these primitive types with at least two elements, or null . Example /* Example of a custom_properties block: // .spr file sprite \"My Test Sprite\" { // ... custom_properties { number_of_layers 8 want_awesomeness true font_name \"GoodNeighbors\" position 100 200 } } */ // It's a good idea to cast the value of the property to the expected type, so // that your script will work reliably regardless of what is in the .spr file! animation = actor . animation ; numberOfLayers = Number ( animation . prop ( \"number_of_layers\" )); // 8 wantAwesomeness = Boolean ( animation . prop ( \"want_awesomeness\" )); // true fontName = String ( animation . prop ( \"font_name\" ) || \"Default Font Name\" ); // \"GoodNeighbors\" foobar = String ( animation . prop ( \"foobar\" ) || \"undefined\" ); // \"undefined\" position = animation . prop ( \"position\" ); if ( typeof position == \"object\" ) { xpos = Number ( position [ 0 ]); // 100 ypos = Number ( position [ 1 ]); // 200 } else { xpos = 0 ; ypos = 0 ; } findTransform findTransform() When a keyframe-based animation is playing, compute an approximation of the transformation applied to the sprite at the current time. You may use this function to make objects follow the transformed sprite or to know its location. If no keyframe-based animation is currently playing, the identity transform will be returned. Available since: Open Surge 0.6.1 Returns Returns a Transform object. Example animationTransform = animation . findTransform (); Console . print ( animationTransform . localPosition );","title":"Animation"},{"location":"engine/animation/#animation","text":"Animation objects are used to gather data about specific animations. Although you can't spawn Animation objects directly, you can access them via other objects such as Actor and Player . Example using SurgeEngine.Actor ; object \"MyExplosion\" is \"entity\" , \"disposable\" , \"private\" { actor = Actor ( \"MyExplosion\" ); state \"main\" { if ( actor . animation . finished ) destroy (); } }","title":"Animation"},{"location":"engine/animation/#properties","text":"","title":"Properties"},{"location":"engine/animation/#id","text":"id : number. The number of the animation, defined in a .spr file.","title":"id"},{"location":"engine/animation/#sprite","text":"sprite : string, read-only. The name of the sprite, defined in a .spr file.","title":"sprite"},{"location":"engine/animation/#exists","text":"exists : boolean, read-only. Will be true if the animation exists, i.e., if its sprite and its animation number have been defined in a .spr file. Available since: Open Surge 0.5.1","title":"exists"},{"location":"engine/animation/#finished","text":"finished : boolean, read-only. Will be true if the animation has finished playing.","title":"finished"},{"location":"engine/animation/#anchor","text":"anchor : Vector2 object, read-only. The hot spot of the animation normalized to [0,1] x [0,1]. Available since: Open Surge 0.6.0","title":"anchor"},{"location":"engine/animation/#hotspot","text":"hotSpot : Vector2 object, read-only. The hot spot of the animation. Coordinates are given in pixels. Note: prior to Open Surge 0.6.0, this property was called hotspot .","title":"hotSpot"},{"location":"engine/animation/#actionspot","text":"actionSpot : Vector2 object, read-only. The action spot of the animation. Coordinates are given in pixels. If the sprite is flipped, the action spot is automatically flipped relative to the hot spot of the animation. Available since: Open Surge 0.6.0","title":"actionSpot"},{"location":"engine/animation/#actionoffset","text":"actionOffset : Vector2 object, read-only. When this vector is added to the position of the sprite, you'll get the position of the action spot . This is suitable to be used with transform.localPosition . Available since: Open Surge 0.6.0","title":"actionOffset"},{"location":"engine/animation/#repeats","text":"repeats : boolean, read-only. Does the animation repeat itself?","title":"repeats"},{"location":"engine/animation/#fps","text":"fps : number, read-only. Frames per second of the animation.","title":"fps"},{"location":"engine/animation/#framecount","text":"frameCount : number, read-only. The number of frames of the animation.","title":"frameCount"},{"location":"engine/animation/#duration","text":"duration : number, read-only. The duration of the animation, in seconds. Available since: Open Surge 0.6.1","title":"duration"},{"location":"engine/animation/#frame","text":"frame : number. The current frame of the animation: an integer between 0 and frameCount - 1 , inclusive.","title":"frame"},{"location":"engine/animation/#speedfactor","text":"speedFactor : number. While the FPS rate controls the speed of the animation, the speed factor gives you an additional degree of control. This is a multiplier that defaults to 1.0, meaning that the animation will run using its normal speed. If it's set to 2.0, it will run using twice that speed. A value of 0.5 means half the speed, and so on.","title":"speedFactor"},{"location":"engine/animation/#sync","text":"sync : boolean. Is the animation is synchronized? A synchronized animation is a repeating animation that displays the same frame across multiple sprites. Defaults to false .","title":"sync"},{"location":"engine/animation/#functions","text":"","title":"Functions"},{"location":"engine/animation/#prop","text":"prop(propertyName) Read the user-defined custom property named propertyName defined in a custom_properties block of the sprite of this animation (.spr file). If the property exists, this function will return a string, a number, a boolean, or an Array of these, depending on the property. If the property does not exist, this function will return null . Available since: Open Surge 0.6.1 Arguments propertyName : string. The name of a custom property. Returns Returns a string, a number, a boolean, an array of these primitive types with at least two elements, or null . Example /* Example of a custom_properties block: // .spr file sprite \"My Test Sprite\" { // ... custom_properties { number_of_layers 8 want_awesomeness true font_name \"GoodNeighbors\" position 100 200 } } */ // It's a good idea to cast the value of the property to the expected type, so // that your script will work reliably regardless of what is in the .spr file! animation = actor . animation ; numberOfLayers = Number ( animation . prop ( \"number_of_layers\" )); // 8 wantAwesomeness = Boolean ( animation . prop ( \"want_awesomeness\" )); // true fontName = String ( animation . prop ( \"font_name\" ) || \"Default Font Name\" ); // \"GoodNeighbors\" foobar = String ( animation . prop ( \"foobar\" ) || \"undefined\" ); // \"undefined\" position = animation . prop ( \"position\" ); if ( typeof position == \"object\" ) { xpos = Number ( position [ 0 ]); // 100 ypos = Number ( position [ 1 ]); // 200 } else { xpos = 0 ; ypos = 0 ; }","title":"prop"},{"location":"engine/animation/#findtransform","text":"findTransform() When a keyframe-based animation is playing, compute an approximation of the transformation applied to the sprite at the current time. You may use this function to make objects follow the transformed sprite or to know its location. If no keyframe-based animation is currently playing, the identity transform will be returned. Available since: Open Surge 0.6.1 Returns Returns a Transform object. Example animationTransform = animation . findTransform (); Console . print ( animationTransform . localPosition );","title":"findTransform"},{"location":"engine/behavior/","text":"Behavior A behavior is an object that, when spawned as a child of an entity , adds a specific behavior to that entity. Example: you can add a behavior to give a Directional Movement to an entity, so you don't need to code that movement yourself. Although the use of behaviors is not mandatory, they greatly simplify the development of your entities. An important aspect of using behaviors is that you can create your own. You can also reuse them in many of your entities and share them with others. Behavior objects should be built in a generic way, so that they can be reused throughout multiple entities. Behavior objects must be tagged behavior and are supposed to be spawned as direct children of entities. They should also implement the protocol (properties, methods) described below. The engine provides a few behaviors by default, and they have been documented in this manual. Example // // The example below shows an entity with 2 behaviors: // // - Enemy: it makes the entity behave like an enemy // (it can hit the player, or be defeated) // // - DirectionalMovement: it makes the entity move // in a certain direction, with a certain speed // using SurgeEngine.Actor ; using SurgeEngine.Vector2 ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.DirectionalMovement ; // Mosquito is a flying baddie object \"Mosquito\" is \"entity\" , \"enemy\" { actor = Actor ( \"Mosquito\" ); enemy = Enemy (); movement = DirectionalMovement (); state \"main\" { actor . hflip = true ; // flip the sprite horizontally movement . direction = Vector2 . left ; movement . speed = 60 ; } } Properties entity entity : object, read-only. The entity associated with this behavior. This is a convenient alias to the parent object. enabled enabled : boolean. Is the behavior enabled? The default value is true , i.e., behaviors are enabled by default.","title":"Behavior"},{"location":"engine/behavior/#behavior","text":"A behavior is an object that, when spawned as a child of an entity , adds a specific behavior to that entity. Example: you can add a behavior to give a Directional Movement to an entity, so you don't need to code that movement yourself. Although the use of behaviors is not mandatory, they greatly simplify the development of your entities. An important aspect of using behaviors is that you can create your own. You can also reuse them in many of your entities and share them with others. Behavior objects should be built in a generic way, so that they can be reused throughout multiple entities. Behavior objects must be tagged behavior and are supposed to be spawned as direct children of entities. They should also implement the protocol (properties, methods) described below. The engine provides a few behaviors by default, and they have been documented in this manual. Example // // The example below shows an entity with 2 behaviors: // // - Enemy: it makes the entity behave like an enemy // (it can hit the player, or be defeated) // // - DirectionalMovement: it makes the entity move // in a certain direction, with a certain speed // using SurgeEngine.Actor ; using SurgeEngine.Vector2 ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.DirectionalMovement ; // Mosquito is a flying baddie object \"Mosquito\" is \"entity\" , \"enemy\" { actor = Actor ( \"Mosquito\" ); enemy = Enemy (); movement = DirectionalMovement (); state \"main\" { actor . hflip = true ; // flip the sprite horizontally movement . direction = Vector2 . left ; movement . speed = 60 ; } }","title":"Behavior"},{"location":"engine/behavior/#properties","text":"","title":"Properties"},{"location":"engine/behavior/#entity","text":"entity : object, read-only. The entity associated with this behavior. This is a convenient alias to the parent object.","title":"entity"},{"location":"engine/behavior/#enabled","text":"enabled : boolean. Is the behavior enabled? The default value is true , i.e., behaviors are enabled by default.","title":"enabled"},{"location":"engine/brick/","text":"Brick The Brick component is used to create brick-like objects, or bricks endowed with scripting capabilities. This allows you to create elevators, conditional barriers (e.g., doors), movable platforms with custom trajectories, and much more. The Brick component only affects collisions. The object that uses it is required to be an entity . This component won't do any rendering. Therefore, it's typically used in conjunction with the Actor component. Example using SurgeEngine.Actor ; using SurgeEngine.Brick ; object \"On/Off Platform\" is \"entity\" { actor = Actor ( \"On/Off Platform\" ); // for rendering brick = Brick ( \"On/Off Platform\" ); // for collision state \"main\" { if ( timeout ( 2.0 )) { brick . enabled = false ; actor . visible = false ; state = \"disabled\" ; } } state \"disabled\" { if ( timeout ( 2.0 )) { brick . enabled = true ; actor . visible = true ; state = \"main\" ; } } } Factory Brick Brick(spriteName) Spawns a new Brick component. Just like regular bricks, a Brick component has a collision mask associated with it. By default, the collision mask will be computed according to the animation 0 of the sprite named spriteName . Arguments spriteName : string. The name of a sprite. Returns A new Brick component. Properties enabled enabled : boolean. Whether the Brick component should affect collisions or not. Defaults to true . type type : string. The type of the Brick component specifies how it affects collisions. This value must be either \"solid\" or \"cloud\" . Defaults to \"solid\" . layer layer : string. Should the Brick component be tied to a specific layer? If so, which layer? This value must be one of the following: \"green\" , \"yellow\" , \"default\" . Defaults to \"default\" . offset offset : Vector2 object. A (x,y) offset relative to the parent object. Defaults to zero.","title":"Brick"},{"location":"engine/brick/#brick","text":"The Brick component is used to create brick-like objects, or bricks endowed with scripting capabilities. This allows you to create elevators, conditional barriers (e.g., doors), movable platforms with custom trajectories, and much more. The Brick component only affects collisions. The object that uses it is required to be an entity . This component won't do any rendering. Therefore, it's typically used in conjunction with the Actor component. Example using SurgeEngine.Actor ; using SurgeEngine.Brick ; object \"On/Off Platform\" is \"entity\" { actor = Actor ( \"On/Off Platform\" ); // for rendering brick = Brick ( \"On/Off Platform\" ); // for collision state \"main\" { if ( timeout ( 2.0 )) { brick . enabled = false ; actor . visible = false ; state = \"disabled\" ; } } state \"disabled\" { if ( timeout ( 2.0 )) { brick . enabled = true ; actor . visible = true ; state = \"main\" ; } } }","title":"Brick"},{"location":"engine/brick/#factory","text":"","title":"Factory"},{"location":"engine/brick/#brick_1","text":"Brick(spriteName) Spawns a new Brick component. Just like regular bricks, a Brick component has a collision mask associated with it. By default, the collision mask will be computed according to the animation 0 of the sprite named spriteName . Arguments spriteName : string. The name of a sprite. Returns A new Brick component.","title":"Brick"},{"location":"engine/brick/#properties","text":"","title":"Properties"},{"location":"engine/brick/#enabled","text":"enabled : boolean. Whether the Brick component should affect collisions or not. Defaults to true .","title":"enabled"},{"location":"engine/brick/#type","text":"type : string. The type of the Brick component specifies how it affects collisions. This value must be either \"solid\" or \"cloud\" . Defaults to \"solid\" .","title":"type"},{"location":"engine/brick/#layer","text":"layer : string. Should the Brick component be tied to a specific layer? If so, which layer? This value must be one of the following: \"green\" , \"yellow\" , \"default\" . Defaults to \"default\" .","title":"layer"},{"location":"engine/brick/#offset","text":"offset : Vector2 object. A (x,y) offset relative to the parent object. Defaults to zero.","title":"offset"},{"location":"engine/camera/","text":"Camera The Camera object can be used to control what content, in world space, is rendered to the screen. The Camera is represented by a 2-dimensional point in world space that is mapped to the center of the screen. Detached entities Entities tagged \"detached\" do not follow the camera. They are rendered in screen space, not in world space. This is useful for creating HUD elements ( Heads-Up Display ). Read more about entities . Example // Import the Camera object using SurgeEngine.Camera ; // Reading the Camera status // This object prints the position of the camera at every second object \"Camera Status\" is \"awake\" , \"entity\" { state \"main\" { if ( timeout ( 1 )) state = \"print\" ; } state \"print\" { Console . print ( Camera . position ); state = \"main\" ; } } Properties position position : Vector2 object. The position of the camera in world space. Tip: use lateUpdate() if you need to change it. Example using SurgeEngine.Camera ; using SurgeEngine.Player ; object \"My Simple Camera\" is \"awake\" , \"entity\" { fun lateUpdate () { player = Player . active ; Camera . position = player . transform . position ; } } locked locked : boolean, read-only. Is the camera locked to a certain area in space? Defaults to false . Functions lock lock(left, top, right, bottom) Locks the camera to a certain rectangular area in space. All coordinates are given in pixels and represent the boundaries of the rectangular area. They are such that left <= right and top <= bottom . Arguments left : number. A x-coordinate in world space. top : number. A y-coordinate in world space. right : number. A x-coordinate in world space. bottom : number. A y-coordinate in world space. unlock unlock() Unlocks the camera. If unlocked, the camera moves freely throughout the space. worldToScreen worldToScreen(position) Converts position from world space to screen space. Screen coordinates are given in pixels. (0,0) is the top-left of the screen and ( Screen.width , Screen.height ) is the bottom-right. Available since: Open Surge 0.5.1 Arguments position : Vector2 object. The position to be converted. Returns Returns a Vector2 object corresponding to the converted coordinates. screenToWorld screenToWorld(position) Converts position from screen space to world space. Screen coordinates are given in pixels. (0,0) is the top-left of the screen and ( Screen.width , Screen.height ) is the bottom-right. Available since: Open Surge 0.5.1 Arguments position : Vector2 object. The position to be converted. Returns Returns a Vector2 object corresponding to the converted coordinates.","title":"Camera"},{"location":"engine/camera/#camera","text":"The Camera object can be used to control what content, in world space, is rendered to the screen. The Camera is represented by a 2-dimensional point in world space that is mapped to the center of the screen. Detached entities Entities tagged \"detached\" do not follow the camera. They are rendered in screen space, not in world space. This is useful for creating HUD elements ( Heads-Up Display ). Read more about entities . Example // Import the Camera object using SurgeEngine.Camera ; // Reading the Camera status // This object prints the position of the camera at every second object \"Camera Status\" is \"awake\" , \"entity\" { state \"main\" { if ( timeout ( 1 )) state = \"print\" ; } state \"print\" { Console . print ( Camera . position ); state = \"main\" ; } }","title":"Camera"},{"location":"engine/camera/#properties","text":"","title":"Properties"},{"location":"engine/camera/#position","text":"position : Vector2 object. The position of the camera in world space. Tip: use lateUpdate() if you need to change it. Example using SurgeEngine.Camera ; using SurgeEngine.Player ; object \"My Simple Camera\" is \"awake\" , \"entity\" { fun lateUpdate () { player = Player . active ; Camera . position = player . transform . position ; } }","title":"position"},{"location":"engine/camera/#locked","text":"locked : boolean, read-only. Is the camera locked to a certain area in space? Defaults to false .","title":"locked"},{"location":"engine/camera/#functions","text":"","title":"Functions"},{"location":"engine/camera/#lock","text":"lock(left, top, right, bottom) Locks the camera to a certain rectangular area in space. All coordinates are given in pixels and represent the boundaries of the rectangular area. They are such that left <= right and top <= bottom . Arguments left : number. A x-coordinate in world space. top : number. A y-coordinate in world space. right : number. A x-coordinate in world space. bottom : number. A y-coordinate in world space.","title":"lock"},{"location":"engine/camera/#unlock","text":"unlock() Unlocks the camera. If unlocked, the camera moves freely throughout the space.","title":"unlock"},{"location":"engine/camera/#worldtoscreen","text":"worldToScreen(position) Converts position from world space to screen space. Screen coordinates are given in pixels. (0,0) is the top-left of the screen and ( Screen.width , Screen.height ) is the bottom-right. Available since: Open Surge 0.5.1 Arguments position : Vector2 object. The position to be converted. Returns Returns a Vector2 object corresponding to the converted coordinates.","title":"worldToScreen"},{"location":"engine/camera/#screentoworld","text":"screenToWorld(position) Converts position from screen space to world space. Screen coordinates are given in pixels. (0,0) is the top-left of the screen and ( Screen.width , Screen.height ) is the bottom-right. Available since: Open Surge 0.5.1 Arguments position : Vector2 object. The position to be converted. Returns Returns a Vector2 object corresponding to the converted coordinates.","title":"screenToWorld"},{"location":"engine/circular_movement/","text":"Circular Movement The Circular Movement behavior makes the associated entity perform a circular orbit on the 2D plane. Its basic parameters are: A radius, given in pixels A movement rate, given in cycles per second Other parameters include: a movement scale in both X and Y axes (making it an elliptic orbit), a flag telling whether the movement should be clockwise or not, and so on. Example // // The example below shows how to make an entity move along // a circle of 128 pixels of radius at a rate of 0.25 cycles // per second (i.e., it takes one second to complete 25% of // a cycle, or 4 seconds to complete a cycle) // using SurgeEngine.Actor ; using SurgeEngine.Vector2 ; using SurgeEngine.Behaviors.CircularMovement ; object \"Simple Ball\" is \"entity\" { actor = Actor ( \"Simple Ball\" ); movement = CircularMovement (); state \"main\" { movement . radius = 128 ; movement . rate = 0.25 ; //movement.scale = Vector2.up; // uncomment to move along the y-axis only } } Factory Behaviors.CircularMovement CircularMovement() Spawns a CircularMovement. Returns A CircularMovement object. Properties radius radius : number. The radius of the movement, in pixels. rate rate : number. The rate of the movement, given in cycles per second. clockwise clockwise : boolean. Indicates whether the movement is clockwise ( true ) or counterclockwise ( false ). Defaults to false . scale scale : Vector2 object. Specifies the scale of the movement in both X and Y axes. It is used to distort the circle. Vector2(1, 1) means no distortion (default). center center : Vector2 object | null . If not null , forces the center of the movement to be at a particular position in world space. Defaults to null . phaseOffset phaseOffset : number. A value in degrees that offsets the current phase . Defaults to zero (180 means opposite phase relative to zero). phase phase : number, read-only. A value in degrees that indicates the current phase of the movement.","title":"CircularMovement"},{"location":"engine/circular_movement/#circular-movement","text":"The Circular Movement behavior makes the associated entity perform a circular orbit on the 2D plane. Its basic parameters are: A radius, given in pixels A movement rate, given in cycles per second Other parameters include: a movement scale in both X and Y axes (making it an elliptic orbit), a flag telling whether the movement should be clockwise or not, and so on. Example // // The example below shows how to make an entity move along // a circle of 128 pixels of radius at a rate of 0.25 cycles // per second (i.e., it takes one second to complete 25% of // a cycle, or 4 seconds to complete a cycle) // using SurgeEngine.Actor ; using SurgeEngine.Vector2 ; using SurgeEngine.Behaviors.CircularMovement ; object \"Simple Ball\" is \"entity\" { actor = Actor ( \"Simple Ball\" ); movement = CircularMovement (); state \"main\" { movement . radius = 128 ; movement . rate = 0.25 ; //movement.scale = Vector2.up; // uncomment to move along the y-axis only } }","title":"Circular Movement"},{"location":"engine/circular_movement/#factory","text":"","title":"Factory"},{"location":"engine/circular_movement/#behaviorscircularmovement","text":"CircularMovement() Spawns a CircularMovement. Returns A CircularMovement object.","title":"Behaviors.CircularMovement"},{"location":"engine/circular_movement/#properties","text":"","title":"Properties"},{"location":"engine/circular_movement/#radius","text":"radius : number. The radius of the movement, in pixels.","title":"radius"},{"location":"engine/circular_movement/#rate","text":"rate : number. The rate of the movement, given in cycles per second.","title":"rate"},{"location":"engine/circular_movement/#clockwise","text":"clockwise : boolean. Indicates whether the movement is clockwise ( true ) or counterclockwise ( false ). Defaults to false .","title":"clockwise"},{"location":"engine/circular_movement/#scale","text":"scale : Vector2 object. Specifies the scale of the movement in both X and Y axes. It is used to distort the circle. Vector2(1, 1) means no distortion (default).","title":"scale"},{"location":"engine/circular_movement/#center","text":"center : Vector2 object | null . If not null , forces the center of the movement to be at a particular position in world space. Defaults to null .","title":"center"},{"location":"engine/circular_movement/#phaseoffset","text":"phaseOffset : number. A value in degrees that offsets the current phase . Defaults to zero (180 means opposite phase relative to zero).","title":"phaseOffset"},{"location":"engine/circular_movement/#phase","text":"phase : number, read-only. A value in degrees that indicates the current phase of the movement.","title":"phase"},{"location":"engine/collider/","text":"Collider A collider, or collision object, is used to detect collisions. There are different types of colliders, each with a different shape. They are usually centered on the hot spot of sprites, but that can be changed by altering their anchor . Colliders must be spawned as children of entities . To detect collisions, you may implement function onCollision() on the entity (see the example below), or use the colliders directly. Additionally, a single entity may have multiple colliders attached to it. This allows users to work with more complex shapes than simple primitives. A collider is an abstract concept, and hence can't be spawned directly. Rather, you can spawn colliders of specific shapes, such as CollisionBox and CollisionBall . All Colliders share some functionalities (detailed in this page), but there are functionalities tied to specific shapes. Example using SurgeEngine.Actor ; using SurgeEngine.Player ; using SurgeEngine.Collisions.CollisionBall ; object \"CollisionDoll\" is \"entity\" { actor = Actor ( \"CollisionDoll\" ); collider = CollisionBall ( 25 ); // ball with radius = 25px // The player has a built-in collider // Let's make it visible for debugging state \"main\" { player = Player . active ; player . collider . visible = true ; collider . visible = true ; } // Detect collisions between a collider that is a child // of this object and any other collider in the game fun onCollision ( otherCollider ) { // A collision has occurred. Console . print ( \"Collided with something\" ); // Collided with a player? if ( otherCollider . entity . hasTag ( \"player\" )) { player = otherCollider . entity ; Console . print ( \"Touched \" + player . name ); } } // While onCollision() catches the moment a collision // first occurs, onOverlap() is called every frame // this collider collides with other collider fun onOverlap ( otherCollider ) { // This function is optional. } } Properties entity entity : object, read-only. The Entity associated with this collider. enabled enabled : boolean. Is the collider enabled? A collider that is not enabled will not notify the parent object if a collision occurs. The default value is true , i.e., colliders are enabled by default. visible visible : boolean. Is the collider visible? This is useful for debugging. The default value is false . anchor anchor : Vector2 object. The anchor of the collider. See also: setAnchor . Available since: Open Surge 0.6.0 Functions collidesWith collidesWith(collider) Checks if this collider is colliding with some other collider. Arguments collider : Collider object. The other collider. Returns Returns true if there is a collision (the colliders overlap), or false otherwise. contains contains(point) Checks if the collider contains the given point, given in world coordinates. Arguments point : Vector2 object. The point to be tested. Returns Returns true if the point is contained in the collider, or false otherwise. setAnchor setAnchor(x, y) Defines the anchor of the collider to be ( x , y ), where these values are (usually) numbers between 0.0 and 1.0. Imagine a bounding box of the collider. Point (0.5, 0.5) is the default, representing its center. Point (0.0, 0.0) is the top-left and (1,0, 1.0), the bottom-right. The anchor of the collider will be aligned to the hot spot of the sprite of the entity. See also: anchor . Arguments x : number. Usually a value between 0.0 and 1.0. y : number. Usually a value between 0.0 and 1.0. Returns Returns the collider itself. Example // ... using SurgeEngine.Collisions.CollisionBox ; object \"CollisionTestObject\" is \"entity\" { // see that the following collision box // has its anchor on pixel (16, 64) collider = CollisionBox ( 32 , 64 ). setAnchor ( 0.5 , 1.0 ); // ... }","title":"Collider"},{"location":"engine/collider/#collider","text":"A collider, or collision object, is used to detect collisions. There are different types of colliders, each with a different shape. They are usually centered on the hot spot of sprites, but that can be changed by altering their anchor . Colliders must be spawned as children of entities . To detect collisions, you may implement function onCollision() on the entity (see the example below), or use the colliders directly. Additionally, a single entity may have multiple colliders attached to it. This allows users to work with more complex shapes than simple primitives. A collider is an abstract concept, and hence can't be spawned directly. Rather, you can spawn colliders of specific shapes, such as CollisionBox and CollisionBall . All Colliders share some functionalities (detailed in this page), but there are functionalities tied to specific shapes. Example using SurgeEngine.Actor ; using SurgeEngine.Player ; using SurgeEngine.Collisions.CollisionBall ; object \"CollisionDoll\" is \"entity\" { actor = Actor ( \"CollisionDoll\" ); collider = CollisionBall ( 25 ); // ball with radius = 25px // The player has a built-in collider // Let's make it visible for debugging state \"main\" { player = Player . active ; player . collider . visible = true ; collider . visible = true ; } // Detect collisions between a collider that is a child // of this object and any other collider in the game fun onCollision ( otherCollider ) { // A collision has occurred. Console . print ( \"Collided with something\" ); // Collided with a player? if ( otherCollider . entity . hasTag ( \"player\" )) { player = otherCollider . entity ; Console . print ( \"Touched \" + player . name ); } } // While onCollision() catches the moment a collision // first occurs, onOverlap() is called every frame // this collider collides with other collider fun onOverlap ( otherCollider ) { // This function is optional. } }","title":"Collider"},{"location":"engine/collider/#properties","text":"","title":"Properties"},{"location":"engine/collider/#entity","text":"entity : object, read-only. The Entity associated with this collider.","title":"entity"},{"location":"engine/collider/#enabled","text":"enabled : boolean. Is the collider enabled? A collider that is not enabled will not notify the parent object if a collision occurs. The default value is true , i.e., colliders are enabled by default.","title":"enabled"},{"location":"engine/collider/#visible","text":"visible : boolean. Is the collider visible? This is useful for debugging. The default value is false .","title":"visible"},{"location":"engine/collider/#anchor","text":"anchor : Vector2 object. The anchor of the collider. See also: setAnchor . Available since: Open Surge 0.6.0","title":"anchor"},{"location":"engine/collider/#functions","text":"","title":"Functions"},{"location":"engine/collider/#collideswith","text":"collidesWith(collider) Checks if this collider is colliding with some other collider. Arguments collider : Collider object. The other collider. Returns Returns true if there is a collision (the colliders overlap), or false otherwise.","title":"collidesWith"},{"location":"engine/collider/#contains","text":"contains(point) Checks if the collider contains the given point, given in world coordinates. Arguments point : Vector2 object. The point to be tested. Returns Returns true if the point is contained in the collider, or false otherwise.","title":"contains"},{"location":"engine/collider/#setanchor","text":"setAnchor(x, y) Defines the anchor of the collider to be ( x , y ), where these values are (usually) numbers between 0.0 and 1.0. Imagine a bounding box of the collider. Point (0.5, 0.5) is the default, representing its center. Point (0.0, 0.0) is the top-left and (1,0, 1.0), the bottom-right. The anchor of the collider will be aligned to the hot spot of the sprite of the entity. See also: anchor . Arguments x : number. Usually a value between 0.0 and 1.0. y : number. Usually a value between 0.0 and 1.0. Returns Returns the collider itself. Example // ... using SurgeEngine.Collisions.CollisionBox ; object \"CollisionTestObject\" is \"entity\" { // see that the following collision box // has its anchor on pixel (16, 64) collider = CollisionBox ( 32 , 64 ). setAnchor ( 0.5 , 1.0 ); // ... }","title":"setAnchor"},{"location":"engine/collisionball/","text":"CollisionBall A CollisionBall is a special type of Collider that takes the shape of a ball. In 2D space, this is a circle with a specific radius. All functions and properties of Collider apply to this. Example using SurgeEngine.Actor ; using SurgeEngine.Collisions.CollisionBall ; object \"CollisionDoll\" is \"entity\" { actor = Actor ( \"CollisionDoll\" ); collider = CollisionBall ( 25 ); // radius = 25px state \"main\" { collider . visible = true ; // useful for debugging } fun onCollision ( otherCollider ) { Console . print ( \"A collision has occurred.\" ); } } Factory Collisions.CollisionBall Collisions.CollisionBall(radius) Spawns a new CollisionBall with the specified radius, in pixels. Arguments radius : number. The radius of the CollisionBall. Returns A new CollisionBall with the specified radius. Properties center center : Vector2 , read-only. The center of the CollisionBall, in world space. radius radius : number. The radius of the CollisionBall, in pixels.","title":"CollisionBall"},{"location":"engine/collisionball/#collisionball","text":"A CollisionBall is a special type of Collider that takes the shape of a ball. In 2D space, this is a circle with a specific radius. All functions and properties of Collider apply to this. Example using SurgeEngine.Actor ; using SurgeEngine.Collisions.CollisionBall ; object \"CollisionDoll\" is \"entity\" { actor = Actor ( \"CollisionDoll\" ); collider = CollisionBall ( 25 ); // radius = 25px state \"main\" { collider . visible = true ; // useful for debugging } fun onCollision ( otherCollider ) { Console . print ( \"A collision has occurred.\" ); } }","title":"CollisionBall"},{"location":"engine/collisionball/#factory","text":"","title":"Factory"},{"location":"engine/collisionball/#collisionscollisionball","text":"Collisions.CollisionBall(radius) Spawns a new CollisionBall with the specified radius, in pixels. Arguments radius : number. The radius of the CollisionBall. Returns A new CollisionBall with the specified radius.","title":"Collisions.CollisionBall"},{"location":"engine/collisionball/#properties","text":"","title":"Properties"},{"location":"engine/collisionball/#center","text":"center : Vector2 , read-only. The center of the CollisionBall, in world space.","title":"center"},{"location":"engine/collisionball/#radius","text":"radius : number. The radius of the CollisionBall, in pixels.","title":"radius"},{"location":"engine/collisionbox/","text":"CollisionBox A CollisionBox is a special type of Collider that takes the shape of a box. In 2D space, this is a rectangle with a specific width and height. All functions and properties of Collider apply to this. Example using SurgeEngine.Actor ; using SurgeEngine.Collisions.CollisionBox ; object \"CollisionDoll\" is \"entity\" { actor = Actor ( \"CollisionDoll\" ); collider = CollisionBox ( 32 , 64 ); // width = 32px, height = 64px state \"main\" { collider . visible = true ; // useful for debugging } fun onCollision ( otherCollider ) { Console . print ( \"A collision has occurred.\" ); } } Factory Collisions.CollisionBox Collisions.CollisionBox(width, height) Spawns a new CollisionBox with the specified dimensions, in pixels. Arguments width : number. The width of the CollisionBox. height : number. The height of the CollisionBox. Returns A new CollisionBox with the specified dimensions. Properties width width : number. The width of the CollisionBox, in pixels. height height : number. The height of the CollisionBox, in pixels. center center : Vector2 , read-only. The center of the CollisionBox, in world space. top top : number, read-only. The y-coordinate of the top border of the CollisionBox, in world space. right right : number, read-only. The x-coordinate of the right border of the CollisionBox, in world space. bottom bottom : number, read-only. The y-coordinate of the bottom border of the CollisionBox, in world space. left left : number, read-only. The x-coordinate of the left border of the CollisionBox, in world space.","title":"CollisionBox"},{"location":"engine/collisionbox/#collisionbox","text":"A CollisionBox is a special type of Collider that takes the shape of a box. In 2D space, this is a rectangle with a specific width and height. All functions and properties of Collider apply to this. Example using SurgeEngine.Actor ; using SurgeEngine.Collisions.CollisionBox ; object \"CollisionDoll\" is \"entity\" { actor = Actor ( \"CollisionDoll\" ); collider = CollisionBox ( 32 , 64 ); // width = 32px, height = 64px state \"main\" { collider . visible = true ; // useful for debugging } fun onCollision ( otherCollider ) { Console . print ( \"A collision has occurred.\" ); } }","title":"CollisionBox"},{"location":"engine/collisionbox/#factory","text":"","title":"Factory"},{"location":"engine/collisionbox/#collisionscollisionbox","text":"Collisions.CollisionBox(width, height) Spawns a new CollisionBox with the specified dimensions, in pixels. Arguments width : number. The width of the CollisionBox. height : number. The height of the CollisionBox. Returns A new CollisionBox with the specified dimensions.","title":"Collisions.CollisionBox"},{"location":"engine/collisionbox/#properties","text":"","title":"Properties"},{"location":"engine/collisionbox/#width","text":"width : number. The width of the CollisionBox, in pixels.","title":"width"},{"location":"engine/collisionbox/#height","text":"height : number. The height of the CollisionBox, in pixels.","title":"height"},{"location":"engine/collisionbox/#center","text":"center : Vector2 , read-only. The center of the CollisionBox, in world space.","title":"center"},{"location":"engine/collisionbox/#top","text":"top : number, read-only. The y-coordinate of the top border of the CollisionBox, in world space.","title":"top"},{"location":"engine/collisionbox/#right","text":"right : number, read-only. The x-coordinate of the right border of the CollisionBox, in world space.","title":"right"},{"location":"engine/collisionbox/#bottom","text":"bottom : number, read-only. The y-coordinate of the bottom border of the CollisionBox, in world space.","title":"bottom"},{"location":"engine/collisionbox/#left","text":"left : number, read-only. The x-coordinate of the left border of the CollisionBox, in world space.","title":"left"},{"location":"engine/delayedevent/","text":"DelayedEvent A DelayedEvent is an event that, when triggered, triggers another event after a specified time has passed. Factory Events.DelayedEvent Events.DelayedEvent(event) Spawns a DelayedEvent. Arguments event : event object. The event to be delayed. Returns A new DelayedEvent that, when triggered, will trigger the specified event after a delay. Example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventList ; using SurgeEngine.Events.DelayedEvent ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : EventList ([ FunctionEvent ( \"Print\" ). withArgument ( \"Hello!\" ), DelayedEvent ( FunctionEvent ( \"Print\" ). withArgument ( \"This is...\" ) ). willWait ( 2.0 ), // wait 2 seconds before triggering this DelayedEvent ( FunctionEvent ( \"Print\" ). withArgument ( \"SurgeScript!\" ) ). willWait ( 4.0 ) // wait 4 seconds before triggering this ]) } }); } } Functions willWait willWait(seconds) Set the delay to trigger the event. Arguments seconds : number. The delay, in seconds. Returns The DelayedEvent object. call call() Triggers the event.","title":"DelayedEvent"},{"location":"engine/delayedevent/#delayedevent","text":"A DelayedEvent is an event that, when triggered, triggers another event after a specified time has passed.","title":"DelayedEvent"},{"location":"engine/delayedevent/#factory","text":"","title":"Factory"},{"location":"engine/delayedevent/#eventsdelayedevent","text":"Events.DelayedEvent(event) Spawns a DelayedEvent. Arguments event : event object. The event to be delayed. Returns A new DelayedEvent that, when triggered, will trigger the specified event after a delay. Example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventList ; using SurgeEngine.Events.DelayedEvent ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : EventList ([ FunctionEvent ( \"Print\" ). withArgument ( \"Hello!\" ), DelayedEvent ( FunctionEvent ( \"Print\" ). withArgument ( \"This is...\" ) ). willWait ( 2.0 ), // wait 2 seconds before triggering this DelayedEvent ( FunctionEvent ( \"Print\" ). withArgument ( \"SurgeScript!\" ) ). willWait ( 4.0 ) // wait 4 seconds before triggering this ]) } }); } }","title":"Events.DelayedEvent"},{"location":"engine/delayedevent/#functions","text":"","title":"Functions"},{"location":"engine/delayedevent/#willwait","text":"willWait(seconds) Set the delay to trigger the event. Arguments seconds : number. The delay, in seconds. Returns The DelayedEvent object.","title":"willWait"},{"location":"engine/delayedevent/#call","text":"call() Triggers the event.","title":"call"},{"location":"engine/directional_movement/","text":"Directional Movement The Directional Movement behavior makes the associated entity perform a directional movement on the 2D plane. It features: A direction vector that specifies the direction of the movement A movement speed, a scalar value given in pixels per second You may control the direction of the movement using the direction vector or an angle given in degrees. Additionally, you may control the speed of the movement simply by changing its value. Directional Movement is very versatile. You can use it to implement many things: different types of baddies, flying objects, racing cars viewed from a top-down view, simple projectiles, and much more. Example // // The example below shows how to make an entity move to the // right of the screen at a rate of 60 pixels per second // using SurgeEngine.Actor ; using SurgeEngine.Vector2 ; using SurgeEngine.Behaviors.DirectionalMovement ; object \"Simple Ball\" is \"entity\" { actor = Actor ( \"Simple Ball\" ); movement = DirectionalMovement (); state \"main\" { movement . direction = Vector2 . right ; movement . speed = 60 ; } } Factory Behaviors.DirectionalMovement DirectionalMovement() Spawns a DirectionalMovement. Returns A DirectionalMovement object. Properties speed speed : number. The speed of the movement, in pixels per second. direction direction : Vector2 object. The direction of the movement. angle angle : number. The counterclockwise angle of the direction vector, in degrees. 0 means right, 90 means up, etc.","title":"DirectionalMovement"},{"location":"engine/directional_movement/#directional-movement","text":"The Directional Movement behavior makes the associated entity perform a directional movement on the 2D plane. It features: A direction vector that specifies the direction of the movement A movement speed, a scalar value given in pixels per second You may control the direction of the movement using the direction vector or an angle given in degrees. Additionally, you may control the speed of the movement simply by changing its value. Directional Movement is very versatile. You can use it to implement many things: different types of baddies, flying objects, racing cars viewed from a top-down view, simple projectiles, and much more. Example // // The example below shows how to make an entity move to the // right of the screen at a rate of 60 pixels per second // using SurgeEngine.Actor ; using SurgeEngine.Vector2 ; using SurgeEngine.Behaviors.DirectionalMovement ; object \"Simple Ball\" is \"entity\" { actor = Actor ( \"Simple Ball\" ); movement = DirectionalMovement (); state \"main\" { movement . direction = Vector2 . right ; movement . speed = 60 ; } }","title":"Directional Movement"},{"location":"engine/directional_movement/#factory","text":"","title":"Factory"},{"location":"engine/directional_movement/#behaviorsdirectionalmovement","text":"DirectionalMovement() Spawns a DirectionalMovement. Returns A DirectionalMovement object.","title":"Behaviors.DirectionalMovement"},{"location":"engine/directional_movement/#properties","text":"","title":"Properties"},{"location":"engine/directional_movement/#speed","text":"speed : number. The speed of the movement, in pixels per second.","title":"speed"},{"location":"engine/directional_movement/#direction","text":"direction : Vector2 object. The direction of the movement.","title":"direction"},{"location":"engine/directional_movement/#angle","text":"angle : number. The counterclockwise angle of the direction vector, in degrees. 0 means right, 90 means up, etc.","title":"angle"},{"location":"engine/enemy/","text":"Enemy The Enemy behavior makes the associated entity behave like an enemy. It will hit the player if touched, unless the player is attacking (jumping, rolling, etc.) In this case the enemy will be destroyed with an explosion, giving the player a certain score. Although the Enemy object generates the described behavior, it is not a concrete enemy itself. You may use it to script your own baddies. Example // // HOW TO SCRIPT A BADDIE: // // 0. Make sure you have the graphics and the sprite file (.spr) ready, // before you begin with SurgeScript // 1. Your object should be tagged (at least): \"entity\", \"enemy\" // 2. Spawn an Actor for the graphics and an Enemy object for the behavior. // using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.Platformer ; object \"My Baddie\" is \"entity\" , \"enemy\" { actor = Actor ( \"My Baddie\" ); // handles the graphics enemy = Enemy (); // handles the behavior platformer = Platformer (). walk (); // make it walk state \"main\" { enemy . score = 100 ; } } Optionally, you may define functions onEnemyAttack(player) and onEnemyDestroy(player) in your entity if you want to catch the events: the enemy has attacked a player and the enemy has been destroyed by the player, respectively. Factory Behaviors.Enemy Enemy() Spawns an Enemy behavior. Returns An Enemy behavior object. Properties score score : number. The score given to the player when the enemy is defeated. invincible invincible : boolean. Is the enemy invincible? An invincible enemy hits the player even when jumping, rolling, etc. - except if the player is also invincible. Defaults to false . collider collider : Collider object, read-only. A collider associated with the enemy. Functions kill kill(player) Destroys the enemy with an explosion, giving score to player . Available since: Open Surge 0.5.1. See the note below. Arguments player : Player object. The player who defeats the enemy. Note: in versions prior to 0.5.1, this function was called getDestroyed . setBounds setBounds(left, top, right, bottom) Set the boundaries of the collider. All coordinates, given in pixels, are relative to the hot spot of the entity. These boundaries are computed automatically, but you may use this function if you need to adjust them. Arguments left : number. Given in pixels. top : number. Given in pixels. right : number. Given in pixels. down : number. Given in pixels. Returns Returns the Enemy behavior itself.","title":"Enemy"},{"location":"engine/enemy/#enemy","text":"The Enemy behavior makes the associated entity behave like an enemy. It will hit the player if touched, unless the player is attacking (jumping, rolling, etc.) In this case the enemy will be destroyed with an explosion, giving the player a certain score. Although the Enemy object generates the described behavior, it is not a concrete enemy itself. You may use it to script your own baddies. Example // // HOW TO SCRIPT A BADDIE: // // 0. Make sure you have the graphics and the sprite file (.spr) ready, // before you begin with SurgeScript // 1. Your object should be tagged (at least): \"entity\", \"enemy\" // 2. Spawn an Actor for the graphics and an Enemy object for the behavior. // using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.Platformer ; object \"My Baddie\" is \"entity\" , \"enemy\" { actor = Actor ( \"My Baddie\" ); // handles the graphics enemy = Enemy (); // handles the behavior platformer = Platformer (). walk (); // make it walk state \"main\" { enemy . score = 100 ; } } Optionally, you may define functions onEnemyAttack(player) and onEnemyDestroy(player) in your entity if you want to catch the events: the enemy has attacked a player and the enemy has been destroyed by the player, respectively.","title":"Enemy"},{"location":"engine/enemy/#factory","text":"","title":"Factory"},{"location":"engine/enemy/#behaviorsenemy","text":"Enemy() Spawns an Enemy behavior. Returns An Enemy behavior object.","title":"Behaviors.Enemy"},{"location":"engine/enemy/#properties","text":"","title":"Properties"},{"location":"engine/enemy/#score","text":"score : number. The score given to the player when the enemy is defeated.","title":"score"},{"location":"engine/enemy/#invincible","text":"invincible : boolean. Is the enemy invincible? An invincible enemy hits the player even when jumping, rolling, etc. - except if the player is also invincible. Defaults to false .","title":"invincible"},{"location":"engine/enemy/#collider","text":"collider : Collider object, read-only. A collider associated with the enemy.","title":"collider"},{"location":"engine/enemy/#functions","text":"","title":"Functions"},{"location":"engine/enemy/#kill","text":"kill(player) Destroys the enemy with an explosion, giving score to player . Available since: Open Surge 0.5.1. See the note below. Arguments player : Player object. The player who defeats the enemy. Note: in versions prior to 0.5.1, this function was called getDestroyed .","title":"kill"},{"location":"engine/enemy/#setbounds","text":"setBounds(left, top, right, bottom) Set the boundaries of the collider. All coordinates, given in pixels, are relative to the hot spot of the entity. These boundaries are computed automatically, but you may use this function if you need to adjust them. Arguments left : number. Given in pixels. top : number. Given in pixels. right : number. Given in pixels. down : number. Given in pixels. Returns Returns the Enemy behavior itself.","title":"setBounds"},{"location":"engine/entity/","text":"Entity An entity is an object that generally is present in the virtual world. Examples include: a pickup item, a gimmick, a non-playable-character, and so on. Entites have special treatment: Entities can have components associated to it. They can be fully customized. By default, they are automatically disabled and moved back to their initial position in the world if they get too far off camera. Behavior can be changed by adding special tags them. The engine will automatically call special functions if you define them. Definition A SurgeScript object is considered to be an entity if it meets all of the following conditions: the object is tagged \"entity\" the object is a direct child of Level or a direct child of another entity Objects that are direct children of entities but that are not tagged \"entity\" are considered to be components . Components are meant to modify the entities in some way. Components may not have any entities as descendants. For example: a child of a component is not considered to be an entity, even if it's tagged \"entity\". Level setup objects and player companion objects are special cases. They are always considered to be entities, regardless if they are tagged \"entity\" or not, for backwards compatibility purposes. Tip During level design, entities may be placed in world space using the editor palette. The icon of the entity will be the first animation (animation 0) of the sprite that has the name of the entity. Tags entity Mark the object as an entity. // In the example below, entity \"My Explosion\" has an Actor // component that gives it visible form: a sprite. using SurgeEngine.Actor ; object \"My Explosion\" is \"entity\" , \"private\" , \"disposable\" { actor = Actor ( \"My Explosion\" ); state \"main\" { if ( actor . animation . finished ) destroy (); } } private Private entities cannot be spawned via the level editor - they will be hidden. awake Don't disable the object nor move it back to its initial position if it gets too far off camera. Performance tip The engine optimizes entities that are not awake by \"putting them to sleep\" whenever they are too far off camera. Take advantage of this optimization by not making your entities awake unless you need to. disposable The engine will automatically destroy the object if it gets too far off camera. detached The object will not follow the camera. It will be rendered in screen space. Effectively detached entities If a non-detached entity is a descendant of a detached entity, the former is effetively detached . Effectively detached entites are rendered just like detached entities. (since 0.6.1) Functions lateUpdate lateUpdate() If lateUpdate() is implemented in your entity, it will be called after all other objects have been updated. This handy function helps order script execution. For example: a routine that controls the Camera should be implemented in lateUpdate() , since it's guaranteed to be executed after other entities have been updated. Available since: Open Surge 0.6.1 Example using SurgeEngine.Camera ; using SurgeEngine.Player ; object \"My Simple Camera\" is \"awake\" , \"entity\" { fun lateUpdate () { player = Player . active ; Camera . position = player . transform . position ; } } onReset onReset() If an entity that is not awake nor detached gets too far off camera, it will be automatically disabled and moved back to its initial position. Whenever that happens, the engine will call this function if it's available in your entity. You may use this function to reset the entity back to its initial state. Note Entities tagged \"awake\" or \"detached\" are not affected by onReset() . Example using SurgeEngine.UI.Text ; // The object below is a simple counter that gets // reseted whenever it gets too far off camera. object \"My Test Counter\" is \"entity\" { label = Text ( \"default\" ); counter = 0 ; state \"main\" { Console . print ( \"Starting the counter...\" ); state = \"wait\" ; } state \"wait\" { label . text = counter ; if ( timeout ( 1.0 )) state = \"increment\" ; } state \"increment\" { counter ++; state = \"wait\" ; } // Without implementing function onReset() below, // the counter would retain its state. fun onReset () { counter = 0 ; state = \"main\" ; } } onLeaveEditor onLeaveEditor() If declared, function onLeaveEditor() will be called whenever the player leaves the level editor and returns to the game. This may be useful to reconfigure your objects.","title":"Entity"},{"location":"engine/entity/#entity","text":"An entity is an object that generally is present in the virtual world. Examples include: a pickup item, a gimmick, a non-playable-character, and so on. Entites have special treatment: Entities can have components associated to it. They can be fully customized. By default, they are automatically disabled and moved back to their initial position in the world if they get too far off camera. Behavior can be changed by adding special tags them. The engine will automatically call special functions if you define them. Definition A SurgeScript object is considered to be an entity if it meets all of the following conditions: the object is tagged \"entity\" the object is a direct child of Level or a direct child of another entity Objects that are direct children of entities but that are not tagged \"entity\" are considered to be components . Components are meant to modify the entities in some way. Components may not have any entities as descendants. For example: a child of a component is not considered to be an entity, even if it's tagged \"entity\". Level setup objects and player companion objects are special cases. They are always considered to be entities, regardless if they are tagged \"entity\" or not, for backwards compatibility purposes. Tip During level design, entities may be placed in world space using the editor palette. The icon of the entity will be the first animation (animation 0) of the sprite that has the name of the entity.","title":"Entity"},{"location":"engine/entity/#tags","text":"","title":"Tags"},{"location":"engine/entity/#entity_1","text":"Mark the object as an entity. // In the example below, entity \"My Explosion\" has an Actor // component that gives it visible form: a sprite. using SurgeEngine.Actor ; object \"My Explosion\" is \"entity\" , \"private\" , \"disposable\" { actor = Actor ( \"My Explosion\" ); state \"main\" { if ( actor . animation . finished ) destroy (); } }","title":"entity"},{"location":"engine/entity/#private","text":"Private entities cannot be spawned via the level editor - they will be hidden.","title":"private"},{"location":"engine/entity/#awake","text":"Don't disable the object nor move it back to its initial position if it gets too far off camera. Performance tip The engine optimizes entities that are not awake by \"putting them to sleep\" whenever they are too far off camera. Take advantage of this optimization by not making your entities awake unless you need to.","title":"awake"},{"location":"engine/entity/#disposable","text":"The engine will automatically destroy the object if it gets too far off camera.","title":"disposable"},{"location":"engine/entity/#detached","text":"The object will not follow the camera. It will be rendered in screen space. Effectively detached entities If a non-detached entity is a descendant of a detached entity, the former is effetively detached . Effectively detached entites are rendered just like detached entities. (since 0.6.1)","title":"detached"},{"location":"engine/entity/#functions","text":"","title":"Functions"},{"location":"engine/entity/#lateupdate","text":"lateUpdate() If lateUpdate() is implemented in your entity, it will be called after all other objects have been updated. This handy function helps order script execution. For example: a routine that controls the Camera should be implemented in lateUpdate() , since it's guaranteed to be executed after other entities have been updated. Available since: Open Surge 0.6.1 Example using SurgeEngine.Camera ; using SurgeEngine.Player ; object \"My Simple Camera\" is \"awake\" , \"entity\" { fun lateUpdate () { player = Player . active ; Camera . position = player . transform . position ; } }","title":"lateUpdate"},{"location":"engine/entity/#onreset","text":"onReset() If an entity that is not awake nor detached gets too far off camera, it will be automatically disabled and moved back to its initial position. Whenever that happens, the engine will call this function if it's available in your entity. You may use this function to reset the entity back to its initial state. Note Entities tagged \"awake\" or \"detached\" are not affected by onReset() . Example using SurgeEngine.UI.Text ; // The object below is a simple counter that gets // reseted whenever it gets too far off camera. object \"My Test Counter\" is \"entity\" { label = Text ( \"default\" ); counter = 0 ; state \"main\" { Console . print ( \"Starting the counter...\" ); state = \"wait\" ; } state \"wait\" { label . text = counter ; if ( timeout ( 1.0 )) state = \"increment\" ; } state \"increment\" { counter ++; state = \"wait\" ; } // Without implementing function onReset() below, // the counter would retain its state. fun onReset () { counter = 0 ; state = \"main\" ; } }","title":"onReset"},{"location":"engine/entity/#onleaveeditor","text":"onLeaveEditor() If declared, function onLeaveEditor() will be called whenever the player leaves the level editor and returns to the game. This may be useful to reconfigure your objects.","title":"onLeaveEditor"},{"location":"engine/entityevent/","text":"EntityEvent An EntityEvent is an event that calls a function of an entity when triggered. Factory Events.EntityEvent Events.EntityEvent Spawns an EntityEvent. Arguments entityID : string. The ID of an entity. Returns A new EntityEvent linked to the specified entity. Example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EntityEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : EntityEvent ( \"aeb587eed1057a5e\" ). willCall ( \"open\" ) } }); } } Functions willCall willCall(functionName) Specifies the name of the function that will be called. Arguments functionName : string. The name of the function that will be called when the event is triggered. Returns The EntityEvent object. withArgument withArgument(data) Adds an argument to the EntityEvent. Arguments added to the EntityEvent will be passed to the entity when the event is triggered - in the order they have been added. To add multiple arguments, call this function multiple times. Arguments data : any. The argument to be added. Returns The EntityEvent object. call call() Triggers the event.","title":"EntityEvent"},{"location":"engine/entityevent/#entityevent","text":"An EntityEvent is an event that calls a function of an entity when triggered.","title":"EntityEvent"},{"location":"engine/entityevent/#factory","text":"","title":"Factory"},{"location":"engine/entityevent/#eventsentityevent","text":"Events.EntityEvent Spawns an EntityEvent. Arguments entityID : string. The ID of an entity. Returns A new EntityEvent linked to the specified entity. Example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EntityEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : EntityEvent ( \"aeb587eed1057a5e\" ). willCall ( \"open\" ) } }); } }","title":"Events.EntityEvent"},{"location":"engine/entityevent/#functions","text":"","title":"Functions"},{"location":"engine/entityevent/#willcall","text":"willCall(functionName) Specifies the name of the function that will be called. Arguments functionName : string. The name of the function that will be called when the event is triggered. Returns The EntityEvent object.","title":"willCall"},{"location":"engine/entityevent/#withargument","text":"withArgument(data) Adds an argument to the EntityEvent. Arguments added to the EntityEvent will be passed to the entity when the event is triggered - in the order they have been added. To add multiple arguments, call this function multiple times. Arguments data : any. The argument to be added. Returns The EntityEvent object.","title":"withArgument"},{"location":"engine/entityevent/#call","text":"call() Triggers the event.","title":"call"},{"location":"engine/event/","text":"Event An event is a function object that is tagged \"event\" . Events are used to run code when triggered. Events let you seamlessly connect entities and write cause and effect relationships. Suppose you have an on/off switch in a level. Whenever that switch is pressed by the player, you want something to happen: raise the water level, open a door, make it rain, teleport the player, and so on. Events are important because they let you decouple the source of the happening (the pressing of the switch) from the results that are experienced (e.g., the raising of the water). Events let you reuse your entities in multiple ways and for multiple purposes. You may design an entity and make it trigger an event, but you do not need to specify in advance what the event actually is. Rather, the concrete event (what must happen) will be configured in your level setup . There are multiple types of events. In practice, you'll use specialized events such as EntityEvent and FunctionEvent when configuring your entities. Event is an empty event that does nothing when triggered, but it should be used when designing your entities, as in the example below. Example // ----------------------------------------------------------------------------- // Using Events // // Note that cause and effect are split into different scripts! // ----------------------------------------------------------------------------- // This script contains an object that will trigger an event whenever a certain // button is pressed (e.g., the jump button). using SurgeEngine.Player ; using SurgeEngine.Events.Event ; object \"Button Detector\" is \"awake\" , \"entity\" { public onButtonPress = Event (); public button = \"fire1\" ; state \"main\" { input = Player . active . input ; if ( input . buttonPressed ( button )) onButtonPress (); } } // ----------------------------------------------------------------------------- // The code below is a different script containing a level setup object. // Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Button Detector\" : { \"button\" : \"fire1\" , // \"fire1\" is the jump button \"onButtonPress\" : FunctionEvent ( \"Print\" ). withArgument ( \"You pressed the button!\" ) } }); } } Factory Events.Event Events.Event() Spawns an empty Event. Returns A new Event. Functions call call() Triggers the event. All event types implement this function.","title":"Event"},{"location":"engine/event/#event","text":"An event is a function object that is tagged \"event\" . Events are used to run code when triggered. Events let you seamlessly connect entities and write cause and effect relationships. Suppose you have an on/off switch in a level. Whenever that switch is pressed by the player, you want something to happen: raise the water level, open a door, make it rain, teleport the player, and so on. Events are important because they let you decouple the source of the happening (the pressing of the switch) from the results that are experienced (e.g., the raising of the water). Events let you reuse your entities in multiple ways and for multiple purposes. You may design an entity and make it trigger an event, but you do not need to specify in advance what the event actually is. Rather, the concrete event (what must happen) will be configured in your level setup . There are multiple types of events. In practice, you'll use specialized events such as EntityEvent and FunctionEvent when configuring your entities. Event is an empty event that does nothing when triggered, but it should be used when designing your entities, as in the example below. Example // ----------------------------------------------------------------------------- // Using Events // // Note that cause and effect are split into different scripts! // ----------------------------------------------------------------------------- // This script contains an object that will trigger an event whenever a certain // button is pressed (e.g., the jump button). using SurgeEngine.Player ; using SurgeEngine.Events.Event ; object \"Button Detector\" is \"awake\" , \"entity\" { public onButtonPress = Event (); public button = \"fire1\" ; state \"main\" { input = Player . active . input ; if ( input . buttonPressed ( button )) onButtonPress (); } } // ----------------------------------------------------------------------------- // The code below is a different script containing a level setup object. // Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Button Detector\" : { \"button\" : \"fire1\" , // \"fire1\" is the jump button \"onButtonPress\" : FunctionEvent ( \"Print\" ). withArgument ( \"You pressed the button!\" ) } }); } }","title":"Event"},{"location":"engine/event/#factory","text":"","title":"Factory"},{"location":"engine/event/#eventsevent","text":"Events.Event() Spawns an empty Event. Returns A new Event.","title":"Events.Event"},{"location":"engine/event/#functions","text":"","title":"Functions"},{"location":"engine/event/#call","text":"call() Triggers the event. All event types implement this function.","title":"call"},{"location":"engine/eventchain/","text":"EventChain An EventChain is an event that triggers other events sequentially, as in a chain of events. Factory Events.EventChain Events.EventChain(chain) Spawns an EventChain. Arguments chain : Array object. A list containing zero or more events. Returns A new EventChain that triggers the specified events, one at a time. The first time the EventChain is triggered, the first event of the chain will be triggered. The second time the EventChain is triggered, the second event of the chain will be triggered, and so on. Note: if the EventChain ever triggers its last event, from that moment onwards it will always trigger its last event (unless you make it loop). Example // EventChain example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventChain ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Switch\" : { \"sticky\" : false , \"onActivate\" : EventChain ([ FunctionEvent ( \"Print\" ). withArgument ( \"First time\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Second time\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Third time\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Enough!\" ) ]) } }); } } Functions willLoop willLoop() Make the EventChain loop. When the last event of the chain is triggered, the next event to be triggered will be the first one. Returns The EventChain object. Example // Triggering Alternating Events // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventChain ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup - Alternating Events\" { fun constructor () { Level . setup ({ \"Switch\" : { \"sticky\" : false , \"onActivate\" : EventChain ([ FunctionEvent ( \"Print\" ). withArgument ( \"Triggered Event A\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Triggered Event B\" ) ]). willLoop () } }); } } call call() Triggers the event.","title":"EventChain"},{"location":"engine/eventchain/#eventchain","text":"An EventChain is an event that triggers other events sequentially, as in a chain of events.","title":"EventChain"},{"location":"engine/eventchain/#factory","text":"","title":"Factory"},{"location":"engine/eventchain/#eventseventchain","text":"Events.EventChain(chain) Spawns an EventChain. Arguments chain : Array object. A list containing zero or more events. Returns A new EventChain that triggers the specified events, one at a time. The first time the EventChain is triggered, the first event of the chain will be triggered. The second time the EventChain is triggered, the second event of the chain will be triggered, and so on. Note: if the EventChain ever triggers its last event, from that moment onwards it will always trigger its last event (unless you make it loop). Example // EventChain example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventChain ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Switch\" : { \"sticky\" : false , \"onActivate\" : EventChain ([ FunctionEvent ( \"Print\" ). withArgument ( \"First time\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Second time\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Third time\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Enough!\" ) ]) } }); } }","title":"Events.EventChain"},{"location":"engine/eventchain/#functions","text":"","title":"Functions"},{"location":"engine/eventchain/#willloop","text":"willLoop() Make the EventChain loop. When the last event of the chain is triggered, the next event to be triggered will be the first one. Returns The EventChain object. Example // Triggering Alternating Events // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventChain ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup - Alternating Events\" { fun constructor () { Level . setup ({ \"Switch\" : { \"sticky\" : false , \"onActivate\" : EventChain ([ FunctionEvent ( \"Print\" ). withArgument ( \"Triggered Event A\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Triggered Event B\" ) ]). willLoop () } }); } }","title":"willLoop"},{"location":"engine/eventchain/#call","text":"call() Triggers the event.","title":"call"},{"location":"engine/eventlist/","text":"EventList An EventList is an event that triggers multiple events when triggered. Factory Events.EventList Events.EventList(list) Spawns an EventList. Arguments list : Array object. A list containing zero or more events. Returns A new EventList that triggers the specified events at once, in the order they have been listed. Example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventList ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : EventList ([ FunctionEvent ( \"Print\" ). withArgument ( \"We're triggering\" ), FunctionEvent ( \"Print\" ). withArgument ( \"multiple events\" ), FunctionEvent ( \"Print\" ). withArgument ( \"at the same time!\" ) ]) } }); } } Functions call call() Triggers the event.","title":"EventList"},{"location":"engine/eventlist/#eventlist","text":"An EventList is an event that triggers multiple events when triggered.","title":"EventList"},{"location":"engine/eventlist/#factory","text":"","title":"Factory"},{"location":"engine/eventlist/#eventseventlist","text":"Events.EventList(list) Spawns an EventList. Arguments list : Array object. A list containing zero or more events. Returns A new EventList that triggers the specified events at once, in the order they have been listed. Example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventList ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : EventList ([ FunctionEvent ( \"Print\" ). withArgument ( \"We're triggering\" ), FunctionEvent ( \"Print\" ). withArgument ( \"multiple events\" ), FunctionEvent ( \"Print\" ). withArgument ( \"at the same time!\" ) ]) } }); } }","title":"Events.EventList"},{"location":"engine/eventlist/#functions","text":"","title":"Functions"},{"location":"engine/eventlist/#call","text":"call() Triggers the event.","title":"call"},{"location":"engine/functionevent/","text":"FunctionEvent A FunctionEvent is an event that calls a function object when triggered. Factory Events.FunctionEvent Events.FunctionEvent(objectName) Spawns a FunctionEvent. Arguments objectName : string. The name of a function object. Returns A new FunctionEvent that, when triggered, calls the specified function object. Example // This is a level setup object. Make // sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : FunctionEvent ( \"Give 1up\" ) } }); } } // ----------------------------------------- // This is a function object that // gives the player one extra life. using SurgeEngine.Player ; using SurgeEngine.Audio.Music ; object \"Give 1up\" { jingle = Music ( \"samples/1up.ogg\" ); fun call () { Player . active . lives += 1 ; jingle . play (); } } Functions withArgument withArgument(data) Adds an argument to the FunctionEvent. Arguments added to the FunctionEvent will be passed to the function object when the event is triggered - in the order they have been added. To add multiple arguments, call this function multiple times. Arguments data : any. The argument to be added. Returns The FunctionEvent object. call call() Triggers the event.","title":"FunctionEvent"},{"location":"engine/functionevent/#functionevent","text":"A FunctionEvent is an event that calls a function object when triggered.","title":"FunctionEvent"},{"location":"engine/functionevent/#factory","text":"","title":"Factory"},{"location":"engine/functionevent/#eventsfunctionevent","text":"Events.FunctionEvent(objectName) Spawns a FunctionEvent. Arguments objectName : string. The name of a function object. Returns A new FunctionEvent that, when triggered, calls the specified function object. Example // This is a level setup object. Make // sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : FunctionEvent ( \"Give 1up\" ) } }); } } // ----------------------------------------- // This is a function object that // gives the player one extra life. using SurgeEngine.Player ; using SurgeEngine.Audio.Music ; object \"Give 1up\" { jingle = Music ( \"samples/1up.ogg\" ); fun call () { Player . active . lives += 1 ; jingle . play (); } }","title":"Events.FunctionEvent"},{"location":"engine/functionevent/#functions","text":"","title":"Functions"},{"location":"engine/functionevent/#withargument","text":"withArgument(data) Adds an argument to the FunctionEvent. Arguments added to the FunctionEvent will be passed to the function object when the event is triggered - in the order they have been added. To add multiple arguments, call this function multiple times. Arguments data : any. The argument to be added. Returns The FunctionEvent object.","title":"withArgument"},{"location":"engine/functionevent/#call","text":"call() Triggers the event.","title":"call"},{"location":"engine/game/","text":"Game Game settings. These are specified in surge.cfg , a file located at the root folder of the game. Available since: Open Surge 0.6.1 Properties title title : string, read-only. The title of the game that is running on the engine. If unspecified, an empty string is returned. version version : string, read-only. The version of the game that is running on the engine. If unspecified, an empty string is returned. Do not confuse it with SurgeEngine.version .","title":"Game"},{"location":"engine/game/#game","text":"Game settings. These are specified in surge.cfg , a file located at the root folder of the game. Available since: Open Surge 0.6.1","title":"Game"},{"location":"engine/game/#properties","text":"","title":"Properties"},{"location":"engine/game/#title","text":"title : string, read-only. The title of the game that is running on the engine. If unspecified, an empty string is returned.","title":"title"},{"location":"engine/game/#version","text":"version : string, read-only. The version of the game that is running on the engine. If unspecified, an empty string is returned. Do not confuse it with SurgeEngine.version .","title":"version"},{"location":"engine/input/","text":"Input The Input object is used to read input from the user. Example using SurgeEngine.Player ; object \"Application\" { player = Player . active ; state \"main\" { if ( player . input . buttonDown ( \"right\" )) Console . print ( \"User is holding right\" ); } } Factory Input Input(inputMap) Spawns a new Input component with the given input map. Note: to read input from a specific character, prefer using Player.input instead. Arguments inputMap : string. The name of the input map. If set to null , a default input map will be used. Returns An Input component. Example using SurgeEngine.Player ; using SurgeEngine.Input ; object \"Application\" { input = Player . active . input ; // this form is preferred (used in most cases) //input = Input(\"custom input map\"); // unless you need to read a custom input map state \"main\" { if ( input . buttonDown ( \"right\" )) Console . print ( \"User is holding right\" ); } } Properties enabled enabled : boolean. Whether the input object is enabled or not. A disabled object does not receive user input. The default value of this property is true . Functions buttonDown buttonDown(buttonName) Checks if a button of the input map is currently being held down. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . Returns Returns true if the specified button is being held down. buttonPressed buttonPressed(buttonName) Checks if a button has just been pressed. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . Returns Returns true if the specified button has just been pressed. buttonReleased buttonReleased(buttonName) Checks if a button has just been released. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . Returns Returns true if the specified button has just been released. simulateButton simulateButton(buttonName, down) Changes the input object so that buttonName will be identified as being held down, or not being held down, in the current frame. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . down : boolean. Should the button be considered as being held down? remap remap(inputMap) Changes the input map. Available since: Open Surge 0.6.1 Arguments inputMap : string. The name of the input map. Returns Returns true on success, or false otherwise.","title":"Input"},{"location":"engine/input/#input","text":"The Input object is used to read input from the user. Example using SurgeEngine.Player ; object \"Application\" { player = Player . active ; state \"main\" { if ( player . input . buttonDown ( \"right\" )) Console . print ( \"User is holding right\" ); } }","title":"Input"},{"location":"engine/input/#factory","text":"","title":"Factory"},{"location":"engine/input/#input_1","text":"Input(inputMap) Spawns a new Input component with the given input map. Note: to read input from a specific character, prefer using Player.input instead. Arguments inputMap : string. The name of the input map. If set to null , a default input map will be used. Returns An Input component. Example using SurgeEngine.Player ; using SurgeEngine.Input ; object \"Application\" { input = Player . active . input ; // this form is preferred (used in most cases) //input = Input(\"custom input map\"); // unless you need to read a custom input map state \"main\" { if ( input . buttonDown ( \"right\" )) Console . print ( \"User is holding right\" ); } }","title":"Input"},{"location":"engine/input/#properties","text":"","title":"Properties"},{"location":"engine/input/#enabled","text":"enabled : boolean. Whether the input object is enabled or not. A disabled object does not receive user input. The default value of this property is true .","title":"enabled"},{"location":"engine/input/#functions","text":"","title":"Functions"},{"location":"engine/input/#buttondown","text":"buttonDown(buttonName) Checks if a button of the input map is currently being held down. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . Returns Returns true if the specified button is being held down.","title":"buttonDown"},{"location":"engine/input/#buttonpressed","text":"buttonPressed(buttonName) Checks if a button has just been pressed. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . Returns Returns true if the specified button has just been pressed.","title":"buttonPressed"},{"location":"engine/input/#buttonreleased","text":"buttonReleased(buttonName) Checks if a button has just been released. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . Returns Returns true if the specified button has just been released.","title":"buttonReleased"},{"location":"engine/input/#simulatebutton","text":"simulateButton(buttonName, down) Changes the input object so that buttonName will be identified as being held down, or not being held down, in the current frame. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . down : boolean. Should the button be considered as being held down?","title":"simulateButton"},{"location":"engine/input/#remap","text":"remap(inputMap) Changes the input map. Available since: Open Surge 0.6.1 Arguments inputMap : string. The name of the input map. Returns Returns true on success, or false otherwise.","title":"remap"},{"location":"engine/lang/","text":"Lang Lang is a SurgeEngine element used to read translation-specific strings, as defined in the language files (.lng). Example using SurgeEngine.Lang ; // Display the current language object \"Application\" { state \"main\" { currentLanguage = Lang [ \"LANG_LANGUAGE\" ]; Console . print ( \"The current language is \" + currentLanguage ); state = \"done\" ; } state \"done\" { } } Functions get get(key) Gets the value of the specified key. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments key : string. The key must always be a string. Returns The translation string associated with the specified key.","title":"Lang"},{"location":"engine/lang/#lang","text":"Lang is a SurgeEngine element used to read translation-specific strings, as defined in the language files (.lng). Example using SurgeEngine.Lang ; // Display the current language object \"Application\" { state \"main\" { currentLanguage = Lang [ \"LANG_LANGUAGE\" ]; Console . print ( \"The current language is \" + currentLanguage ); state = \"done\" ; } state \"done\" { } }","title":"Lang"},{"location":"engine/lang/#functions","text":"","title":"Functions"},{"location":"engine/lang/#get","text":"get(key) Gets the value of the specified key. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments key : string. The key must always be a string. Returns The translation string associated with the specified key.","title":"get"},{"location":"engine/level/","text":"Level Level routines. A level is a scene in the game, stored as a .lev file in the levels/ folder. Whenever you spawn an object in SurgeScript, you must keep a reference to it, otherwise it will be automatically deleted by the Garbage Collector . Sometimes you want to spawn entities in your level, but keeping references to all of them is inconvenient. In this case, you can spawn them as children of the Level object . It will keep the references for you, and thus they won't be garbage collected. Example using SurgeEngine.Actor ; using SurgeEngine.Level ; using SurgeEngine.Vector2 ; object \"Application\" { state \"main\" { createExplosionAt ( 100 , 200 ); state = \"wait\" ; } state \"wait\" { if ( timeout ( 1.0 )) state = \"main\" ; } fun createExplosionAt ( x , y ) { position = Vector2 ( x , y ); return Level . spawnEntity ( \"MyExplosion\" , position ); // no need to keep references } } object \"MyExplosion\" is \"entity\" , \"disposable\" , \"private\" { actor = Actor ( \"MyExplosion\" ); state \"main\" { if ( actor . animation . finished ) destroy () } } Properties name name : string, read-only. The name of the level. Example using SurgeEngine.Level ; // Will display the name of the level object \"Application\" { state \"main\" { Console . print ( Level . name ); state = \"done\" ; } state \"done\" { } } act act : number. The act number (1, 2, 3...) of the current level. Note: this property is writable since Open Surge 0.6.1. cleared cleared : boolean, read-only. Checks if the current level has been cleared by the player. If this is true , a level cleared animation should be played. Although the engine provides a default animation, you may use this property to design your own. See also: clear . file file : string, read-only. The relative path of the .lev file of the current level. version version : string, read-only. The version of the level, defined in the .lev file. author author : string, read-only. The author of the level, defined in the .lev file. license license : string, read-only. The license of the level, defined in the .lev file. music music : Music object, read-only. The music of the level. bgtheme bgtheme : string, read-only. The path to the original background file (.bg), as declared in the .lev file. background background : string. The path to the background file (.bg) currently in use. Use this property to change the background of the level. waterlevel waterlevel : number. The y-coordinate, in world space, of the level water. Pixels not above this value are underwater. spawnpoint spawnpoint : Vector2 object. The position where the player is placed when the level starts. gravity gravity : number, read-only. The acceleration of gravity, measured in pixels per second squared. time time : number. Elapsed time in the level, given in seconds. The level time will be frozen if the cleared flag is set or if the player is dying. Note: this property is writable since Open Surge 0.6.0. next next : number. The number of the next level in the current quest: 1 means the first level of the quest, 2 means the second, and so on. onUnload onUnload : object | null . Used to specify a function object to be called when the level is unloaded. debugMode debugMode : boolean. Whether or not the Debug Mode is activated. Available since: Open Surge 0.6.1 Functions spawn spawn(objectName) Spawns an object as a child of Level. Such objects won't be garbage collected. Use spawnEntity instead if you intend to spawn an entity . Arguments objectName : string. The name of the object to be spawned. Returns The spawned object. spawnEntity spawnEntity(objectName, position) Spawns an entity named objectName at a certain position . The entity won't be garbage collected, as in spawn . Arguments objectName : string. The name of the entity to be spawned. position : Vector2 object. The position of the entity. Returns The spawned entity object. entity entity(entityId) Entities spawned with spawnEntity are automatically assigned an ID, a hexadecimal identification string. The purpose of the ID is to uniquely identify the entity in the level. This function returns the entity whose ID is entityId . Arguments entityId : string. The ID of the entity to be retrieved. Returns The desired entity object, or null if there is no entity associated with the given ID. Example using SurgeEngine.Level ; // // Level.entity() is very useful when creating setup objects, i.e., // objects spawned when the level is initialized. You can use it to // tune the parameters of specific entities, call their functions, etc. // // The example below can be added to the startup list in the .lev file. // object \"My Setup Object\" { state \"main\" { // setup the entity item = Level . entity ( \"ab65d8fe1ebd68de\" ); // first, we get the entity if ( item != null ) { Console . print ( item . __name ); // then we print the object name //item.score = 100; // we can also change a property } else Console . print ( \"Entity not found\" ); // change the state state = \"done\" ; } state \"done\" { } } entityId entityId(entityObject) Returns the ID of the provided entity , if it is defined. If no such ID is defined, an empty string is returned. Available since: Open Surge 0.6.1 Arguments entityObject : object. An entity. Returns A string with a hexadecimal identification code, or an empty string. findEntity findEntity(entityName) Finds an entity named entityName spawned with spawnEntity . Available since: Open Surge 0.6.1 Arguments entityName : string. The name of an entity object. Returns An entity named entityName , or null if there is none. findEntities findEntities(entityName) Finds all entities named entityName spawned with spawnEntity . Available since: Open Surge 0.6.1 Arguments entityName : string. The name of the entities to be searched. Returns A new array containing all entities named entityName . If none are found, an empty array is returned. activeEntities activeEntities() Finds all active entities, i.e.: those that are near the camera, as well as all awake and detached ones. Available since: Open Surge 0.6.1 Returns A new array containing active entities. If none are found, an empty array is returned. setup setup(config) Sets up the properties of a collection of level objects. This is a handy function typically used in a startup object of your level. Its purpose is to configure the properties of level objects. You may set the properties of groups of objects (given their names) and of individual entities alone (given their IDs). The target properties and their respective values should be specified in the config Dictionary , passed as a parameter. Each key of config should be either an object name or an entity ID. Each value of the dictionary should be another dictionary specifying the properties to be set and their respective values. If an object name is specified in a key of config , all level objects with that name will be affected. If an entity ID is provided, only that specific entity will be affected, if it exists. This function will search for all the specified objects in the level, so it's not supposed to be used in a loop (or in a repeating state). Furthermore, if one or more objects or properties do not exist, this function will fail silently. Therefore, make sure you type everything correctly. Arguments config : Dictionary object. The configuration as described. Example using SurgeEngine.Level ; // // This is supposed to be a startup object, // listed in the startup list of a .lev file // object \"My Level Setup\" { // setup properties fun constructor () { Level . setup ({ \"Elevator\" : { \"anim\" : 2 }, \"Background Exchanger\" : { \"background\" : \"themes/template.bg\" }, \"5640353a6efd2901\" : { \"someProperty\" : 123 , \"someOtherProperty\" : \"hello\" }, \"770ae26584229af2\" : { \"title\" : \"Super!!\" , \"message\" : \"Hey there! Feeling good today?\" , \"buttons\" : [ \"Yes\" , \"No\" ] } }); } } restart restart() Restarts the current level. quit quit() Prompts the user to see if he/she wants to quit the current level. Deprecated since: Open Surge 0.6.1 abort abort() Quits the current level/quest without prompting the user. pause pause() Pauses the game. load load(filepath) Loads the specified level/quest. If you pass the path to a level (a .lev file in the levels/ folder), that level will be loaded. The state of the current level (position of the entities and so on) will be lost. If you pass the path to a quest (a .qst file in the quests/ folder), that quest will be loaded and, when it's completed or aborted, the engine will redirect the user back to the level he/she was before. Arguments filepath : string. Relative path of the level or quest to be loaded. Example using SurgeEngine.Level ; object \"My Level Loader\" { fun load ( id ) { if ( id == \"beach\" ) { Level . load ( \"levels/beach_level.lev\" ); } else if ( id == \"forest\" ) { Level . load ( \"levels/forest_level.lev\" ); } else if ( id == \"bonus\" ) { Level . next -= 1 ; // return to the current level after completing the bonus Level . load ( \"levels/bonus_stage.lev\" ); } else Console . print ( \"Unrecognized level: \" + id ); } } loadAndReturn loadAndReturn(filepath) Loads the specified level or quest and, after completing or exiting the loaded scene, returns to the level the player was before. If you pass the path to a quest, this function behaves exactly like load() . Available since: Open Surge 0.6.1 Arguments filepath : string. Relative path of the level or quest to be loaded. Example // Load a bonus stage and return to the current level if the player completes it or exits from it Level . loadAndReturn ( \"levels/bonus_stage.lev\" ); loadNext loadNext() Loads the next level in the current quest. This is the usual procedure after clearing the level . See also: next . clear clear() Sets the cleared flag and disables player input. See also: cleared , undoClear . undoClear undoClear() Reverses a previous call to clear , disabling the cleared flag and enabling player input again. This is typically used to play a cutscene after a level cleared animation or to have multiple acts in the same level file. See also: cleared , clear , act . Available since: Open Surge 0.6.1","title":"Level"},{"location":"engine/level/#level","text":"Level routines. A level is a scene in the game, stored as a .lev file in the levels/ folder. Whenever you spawn an object in SurgeScript, you must keep a reference to it, otherwise it will be automatically deleted by the Garbage Collector . Sometimes you want to spawn entities in your level, but keeping references to all of them is inconvenient. In this case, you can spawn them as children of the Level object . It will keep the references for you, and thus they won't be garbage collected. Example using SurgeEngine.Actor ; using SurgeEngine.Level ; using SurgeEngine.Vector2 ; object \"Application\" { state \"main\" { createExplosionAt ( 100 , 200 ); state = \"wait\" ; } state \"wait\" { if ( timeout ( 1.0 )) state = \"main\" ; } fun createExplosionAt ( x , y ) { position = Vector2 ( x , y ); return Level . spawnEntity ( \"MyExplosion\" , position ); // no need to keep references } } object \"MyExplosion\" is \"entity\" , \"disposable\" , \"private\" { actor = Actor ( \"MyExplosion\" ); state \"main\" { if ( actor . animation . finished ) destroy () } }","title":"Level"},{"location":"engine/level/#properties","text":"","title":"Properties"},{"location":"engine/level/#name","text":"name : string, read-only. The name of the level. Example using SurgeEngine.Level ; // Will display the name of the level object \"Application\" { state \"main\" { Console . print ( Level . name ); state = \"done\" ; } state \"done\" { } }","title":"name"},{"location":"engine/level/#act","text":"act : number. The act number (1, 2, 3...) of the current level. Note: this property is writable since Open Surge 0.6.1.","title":"act"},{"location":"engine/level/#cleared","text":"cleared : boolean, read-only. Checks if the current level has been cleared by the player. If this is true , a level cleared animation should be played. Although the engine provides a default animation, you may use this property to design your own. See also: clear .","title":"cleared"},{"location":"engine/level/#file","text":"file : string, read-only. The relative path of the .lev file of the current level.","title":"file"},{"location":"engine/level/#version","text":"version : string, read-only. The version of the level, defined in the .lev file.","title":"version"},{"location":"engine/level/#author","text":"author : string, read-only. The author of the level, defined in the .lev file.","title":"author"},{"location":"engine/level/#license","text":"license : string, read-only. The license of the level, defined in the .lev file.","title":"license"},{"location":"engine/level/#music","text":"music : Music object, read-only. The music of the level.","title":"music"},{"location":"engine/level/#bgtheme","text":"bgtheme : string, read-only. The path to the original background file (.bg), as declared in the .lev file.","title":"bgtheme"},{"location":"engine/level/#background","text":"background : string. The path to the background file (.bg) currently in use. Use this property to change the background of the level.","title":"background"},{"location":"engine/level/#waterlevel","text":"waterlevel : number. The y-coordinate, in world space, of the level water. Pixels not above this value are underwater.","title":"waterlevel"},{"location":"engine/level/#spawnpoint","text":"spawnpoint : Vector2 object. The position where the player is placed when the level starts.","title":"spawnpoint"},{"location":"engine/level/#gravity","text":"gravity : number, read-only. The acceleration of gravity, measured in pixels per second squared.","title":"gravity"},{"location":"engine/level/#time","text":"time : number. Elapsed time in the level, given in seconds. The level time will be frozen if the cleared flag is set or if the player is dying. Note: this property is writable since Open Surge 0.6.0.","title":"time"},{"location":"engine/level/#next","text":"next : number. The number of the next level in the current quest: 1 means the first level of the quest, 2 means the second, and so on.","title":"next"},{"location":"engine/level/#onunload","text":"onUnload : object | null . Used to specify a function object to be called when the level is unloaded.","title":"onUnload"},{"location":"engine/level/#debugmode","text":"debugMode : boolean. Whether or not the Debug Mode is activated. Available since: Open Surge 0.6.1","title":"debugMode"},{"location":"engine/level/#functions","text":"","title":"Functions"},{"location":"engine/level/#spawn","text":"spawn(objectName) Spawns an object as a child of Level. Such objects won't be garbage collected. Use spawnEntity instead if you intend to spawn an entity . Arguments objectName : string. The name of the object to be spawned. Returns The spawned object.","title":"spawn"},{"location":"engine/level/#spawnentity","text":"spawnEntity(objectName, position) Spawns an entity named objectName at a certain position . The entity won't be garbage collected, as in spawn . Arguments objectName : string. The name of the entity to be spawned. position : Vector2 object. The position of the entity. Returns The spawned entity object.","title":"spawnEntity"},{"location":"engine/level/#entity","text":"entity(entityId) Entities spawned with spawnEntity are automatically assigned an ID, a hexadecimal identification string. The purpose of the ID is to uniquely identify the entity in the level. This function returns the entity whose ID is entityId . Arguments entityId : string. The ID of the entity to be retrieved. Returns The desired entity object, or null if there is no entity associated with the given ID. Example using SurgeEngine.Level ; // // Level.entity() is very useful when creating setup objects, i.e., // objects spawned when the level is initialized. You can use it to // tune the parameters of specific entities, call their functions, etc. // // The example below can be added to the startup list in the .lev file. // object \"My Setup Object\" { state \"main\" { // setup the entity item = Level . entity ( \"ab65d8fe1ebd68de\" ); // first, we get the entity if ( item != null ) { Console . print ( item . __name ); // then we print the object name //item.score = 100; // we can also change a property } else Console . print ( \"Entity not found\" ); // change the state state = \"done\" ; } state \"done\" { } }","title":"entity"},{"location":"engine/level/#entityid","text":"entityId(entityObject) Returns the ID of the provided entity , if it is defined. If no such ID is defined, an empty string is returned. Available since: Open Surge 0.6.1 Arguments entityObject : object. An entity. Returns A string with a hexadecimal identification code, or an empty string.","title":"entityId"},{"location":"engine/level/#findentity","text":"findEntity(entityName) Finds an entity named entityName spawned with spawnEntity . Available since: Open Surge 0.6.1 Arguments entityName : string. The name of an entity object. Returns An entity named entityName , or null if there is none.","title":"findEntity"},{"location":"engine/level/#findentities","text":"findEntities(entityName) Finds all entities named entityName spawned with spawnEntity . Available since: Open Surge 0.6.1 Arguments entityName : string. The name of the entities to be searched. Returns A new array containing all entities named entityName . If none are found, an empty array is returned.","title":"findEntities"},{"location":"engine/level/#activeentities","text":"activeEntities() Finds all active entities, i.e.: those that are near the camera, as well as all awake and detached ones. Available since: Open Surge 0.6.1 Returns A new array containing active entities. If none are found, an empty array is returned.","title":"activeEntities"},{"location":"engine/level/#setup","text":"setup(config) Sets up the properties of a collection of level objects. This is a handy function typically used in a startup object of your level. Its purpose is to configure the properties of level objects. You may set the properties of groups of objects (given their names) and of individual entities alone (given their IDs). The target properties and their respective values should be specified in the config Dictionary , passed as a parameter. Each key of config should be either an object name or an entity ID. Each value of the dictionary should be another dictionary specifying the properties to be set and their respective values. If an object name is specified in a key of config , all level objects with that name will be affected. If an entity ID is provided, only that specific entity will be affected, if it exists. This function will search for all the specified objects in the level, so it's not supposed to be used in a loop (or in a repeating state). Furthermore, if one or more objects or properties do not exist, this function will fail silently. Therefore, make sure you type everything correctly. Arguments config : Dictionary object. The configuration as described. Example using SurgeEngine.Level ; // // This is supposed to be a startup object, // listed in the startup list of a .lev file // object \"My Level Setup\" { // setup properties fun constructor () { Level . setup ({ \"Elevator\" : { \"anim\" : 2 }, \"Background Exchanger\" : { \"background\" : \"themes/template.bg\" }, \"5640353a6efd2901\" : { \"someProperty\" : 123 , \"someOtherProperty\" : \"hello\" }, \"770ae26584229af2\" : { \"title\" : \"Super!!\" , \"message\" : \"Hey there! Feeling good today?\" , \"buttons\" : [ \"Yes\" , \"No\" ] } }); } }","title":"setup"},{"location":"engine/level/#restart","text":"restart() Restarts the current level.","title":"restart"},{"location":"engine/level/#quit","text":"quit() Prompts the user to see if he/she wants to quit the current level. Deprecated since: Open Surge 0.6.1","title":"quit"},{"location":"engine/level/#abort","text":"abort() Quits the current level/quest without prompting the user.","title":"abort"},{"location":"engine/level/#pause","text":"pause() Pauses the game.","title":"pause"},{"location":"engine/level/#load","text":"load(filepath) Loads the specified level/quest. If you pass the path to a level (a .lev file in the levels/ folder), that level will be loaded. The state of the current level (position of the entities and so on) will be lost. If you pass the path to a quest (a .qst file in the quests/ folder), that quest will be loaded and, when it's completed or aborted, the engine will redirect the user back to the level he/she was before. Arguments filepath : string. Relative path of the level or quest to be loaded. Example using SurgeEngine.Level ; object \"My Level Loader\" { fun load ( id ) { if ( id == \"beach\" ) { Level . load ( \"levels/beach_level.lev\" ); } else if ( id == \"forest\" ) { Level . load ( \"levels/forest_level.lev\" ); } else if ( id == \"bonus\" ) { Level . next -= 1 ; // return to the current level after completing the bonus Level . load ( \"levels/bonus_stage.lev\" ); } else Console . print ( \"Unrecognized level: \" + id ); } }","title":"load"},{"location":"engine/level/#loadandreturn","text":"loadAndReturn(filepath) Loads the specified level or quest and, after completing or exiting the loaded scene, returns to the level the player was before. If you pass the path to a quest, this function behaves exactly like load() . Available since: Open Surge 0.6.1 Arguments filepath : string. Relative path of the level or quest to be loaded. Example // Load a bonus stage and return to the current level if the player completes it or exits from it Level . loadAndReturn ( \"levels/bonus_stage.lev\" );","title":"loadAndReturn"},{"location":"engine/level/#loadnext","text":"loadNext() Loads the next level in the current quest. This is the usual procedure after clearing the level . See also: next .","title":"loadNext"},{"location":"engine/level/#clear","text":"clear() Sets the cleared flag and disables player input. See also: cleared , undoClear .","title":"clear"},{"location":"engine/level/#undoclear","text":"undoClear() Reverses a previous call to clear , disabling the cleared flag and enabling player input again. This is typically used to play a cutscene after a level cleared animation or to have multiple acts in the same level file. See also: cleared , clear , act . Available since: Open Surge 0.6.1","title":"undoClear"},{"location":"engine/mobile_gamepad/","text":"MobileGamepad The mobile gamepad is a virtual gamepad that appears on the screen when the engine is launched in mobile mode . Available since: Open Surge 0.6.1 Properties visible visible : boolean, read-only. Whether or not the mobile gamepad is visible. Functions fadeIn fadeIn() Makes the mobile gamepad appear smoothly. fadeOut fadeOut() Makes the mobile gamepad disappear smoothly.","title":"MobileGamepad"},{"location":"engine/mobile_gamepad/#mobilegamepad","text":"The mobile gamepad is a virtual gamepad that appears on the screen when the engine is launched in mobile mode . Available since: Open Surge 0.6.1","title":"MobileGamepad"},{"location":"engine/mobile_gamepad/#properties","text":"","title":"Properties"},{"location":"engine/mobile_gamepad/#visible","text":"visible : boolean, read-only. Whether or not the mobile gamepad is visible.","title":"visible"},{"location":"engine/mobile_gamepad/#functions","text":"","title":"Functions"},{"location":"engine/mobile_gamepad/#fadein","text":"fadeIn() Makes the mobile gamepad appear smoothly.","title":"fadeIn"},{"location":"engine/mobile_gamepad/#fadeout","text":"fadeOut() Makes the mobile gamepad disappear smoothly.","title":"fadeOut"},{"location":"engine/mouse/","text":"Mouse The Mouse object is used to read input from the mouse. Example // This example shows how to use a sprite // as a mouse cursor. Since My Cursor is // tagged \"detached\", it will be rendered // in screen space, not in world space. using SurgeEngine.Actor ; using SurgeEngine.Transform ; using SurgeEngine.Input.Mouse ; object \"My Cursor\" is \"entity\" , \"detached\" { actor = Actor ( \"My Cursor\" ); transform = Transform (); state \"main\" { transform . position = Mouse . position ; if ( Mouse . buttonPressed ( \"left\" )) Console . print ( \"left click\" ); } fun constructor () { actor . zindex = 1.0 ; } } Properties position position : Vector2 object, read-only. The position of the mouse cursor, in screen space. scrollUp scrollUp : boolean, read-only. Will be true at the frame the user scrolls up using the mouse wheel. Available since: Open Surge 0.5.1 scrollDown scrollDown : boolean, read-only. Will be true at the frame the user scrolls down using the mouse wheel. Available since: Open Surge 0.5.1 Functions buttonDown buttonDown(buttonName) Checks if a mouse button is currently being held down. Arguments buttonName : string. One of the following: \"left\" , \"right\" , \"middle\" . Returns Returns true if the specified button is being held down. buttonPressed buttonPressed(buttonName) Checks if a mouse button has just been pressed. Arguments buttonName : string. One of the following: \"left\" , \"right\" , \"middle\" . Returns Returns true if the specified button has just been pressed (i.e., a click has just occurred). Example using SurgeEngine.Input.Mouse ; using SurgeEngine.Collisions.CollisionBall ; using SurgeEngine.Transform ; using SurgeEngine.Camera ; // Use the mouse cursor to click on any entity that has a collider. // Setup: simply place this object on the level. object \"Entity Picker\" is \"awake\" , \"entity\" { transform = Transform (); collider = CollisionBall ( 8 ); state \"main\" { transform . position = Camera . screenToWorld ( Mouse . position ); collider . visible = true ; } fun onOverlap ( otherCollider ) { if ( Mouse . buttonPressed ( \"left\" )) Console . print ( \"Clicked on \" + otherCollider . entity . __name ); } } buttonReleased buttonReleased(buttonName) Checks if a mouse button has just been released. Arguments buttonName : string. One of the following: \"left\" , \"right\" , \"middle\" . Returns Returns true if the specified button has just been released.","title":"Mouse"},{"location":"engine/mouse/#mouse","text":"The Mouse object is used to read input from the mouse. Example // This example shows how to use a sprite // as a mouse cursor. Since My Cursor is // tagged \"detached\", it will be rendered // in screen space, not in world space. using SurgeEngine.Actor ; using SurgeEngine.Transform ; using SurgeEngine.Input.Mouse ; object \"My Cursor\" is \"entity\" , \"detached\" { actor = Actor ( \"My Cursor\" ); transform = Transform (); state \"main\" { transform . position = Mouse . position ; if ( Mouse . buttonPressed ( \"left\" )) Console . print ( \"left click\" ); } fun constructor () { actor . zindex = 1.0 ; } }","title":"Mouse"},{"location":"engine/mouse/#properties","text":"","title":"Properties"},{"location":"engine/mouse/#position","text":"position : Vector2 object, read-only. The position of the mouse cursor, in screen space.","title":"position"},{"location":"engine/mouse/#scrollup","text":"scrollUp : boolean, read-only. Will be true at the frame the user scrolls up using the mouse wheel. Available since: Open Surge 0.5.1","title":"scrollUp"},{"location":"engine/mouse/#scrolldown","text":"scrollDown : boolean, read-only. Will be true at the frame the user scrolls down using the mouse wheel. Available since: Open Surge 0.5.1","title":"scrollDown"},{"location":"engine/mouse/#functions","text":"","title":"Functions"},{"location":"engine/mouse/#buttondown","text":"buttonDown(buttonName) Checks if a mouse button is currently being held down. Arguments buttonName : string. One of the following: \"left\" , \"right\" , \"middle\" . Returns Returns true if the specified button is being held down.","title":"buttonDown"},{"location":"engine/mouse/#buttonpressed","text":"buttonPressed(buttonName) Checks if a mouse button has just been pressed. Arguments buttonName : string. One of the following: \"left\" , \"right\" , \"middle\" . Returns Returns true if the specified button has just been pressed (i.e., a click has just occurred). Example using SurgeEngine.Input.Mouse ; using SurgeEngine.Collisions.CollisionBall ; using SurgeEngine.Transform ; using SurgeEngine.Camera ; // Use the mouse cursor to click on any entity that has a collider. // Setup: simply place this object on the level. object \"Entity Picker\" is \"awake\" , \"entity\" { transform = Transform (); collider = CollisionBall ( 8 ); state \"main\" { transform . position = Camera . screenToWorld ( Mouse . position ); collider . visible = true ; } fun onOverlap ( otherCollider ) { if ( Mouse . buttonPressed ( \"left\" )) Console . print ( \"Clicked on \" + otherCollider . entity . __name ); } }","title":"buttonPressed"},{"location":"engine/mouse/#buttonreleased","text":"buttonReleased(buttonName) Checks if a mouse button has just been released. Arguments buttonName : string. One of the following: \"left\" , \"right\" , \"middle\" . Returns Returns true if the specified button has just been released.","title":"buttonReleased"},{"location":"engine/music/","text":"Music The Music object lets you play music. This is meant to handle background music; therefore, only one music can be played at a time. Unlike regular sounds , musics are streamed, (i.e., not loaded completely in memory). Given the longer nature of musics, this improves memory usage and helps with the loading times. Example using SurgeEngine.Level ; // Fades the music in a linear fashion ;) object \"MyMusicFader\" { public music = Level . music ; prevVolume = music . volume ; fadeTime = 1.0 ; // given in seconds state \"main\" { } state \"fadeout\" { music . volume -= Time . delta / fadeTime ; if ( music . volume <= 0.0 ) { music . pause (); music . volume = prevVolume ; state = \"main\" ; } } // call fadeOut() to make the // music fade smoothly fun fadeOut ( seconds ) { if ( state == \"main\" ) prevVolume = music . volume ; fadeTime = seconds ; state = \"fadeout\" ; } } Factory Music Audio.Music(path) Creates a Music object associated with a certain file. Arguments path : string. The path of the music - usually a file in the musics/ folder. Returns A Music object. Example using SurgeEngine.Audio.Music ; object \"MusicTest\" { music = Music ( \"musics/options.ogg\" ); state \"main\" { // loop music if (! music . playing ) music . play (); } } Properties playing playing : boolean, read-only. Will be true if the music is playing. volume volume : number. The volume of the music, a value between 0.0 and 1.0, inclusive (zero means silence). Functions play play() Plays the music (once). To make it loop, play it whenever music.playing is false . stop stop() Stops the music. Once the music is stopped, it can only be played again from the beginning. pause pause() Pauses the music. A paused music can be resumed later with play() .","title":"Music"},{"location":"engine/music/#music","text":"The Music object lets you play music. This is meant to handle background music; therefore, only one music can be played at a time. Unlike regular sounds , musics are streamed, (i.e., not loaded completely in memory). Given the longer nature of musics, this improves memory usage and helps with the loading times. Example using SurgeEngine.Level ; // Fades the music in a linear fashion ;) object \"MyMusicFader\" { public music = Level . music ; prevVolume = music . volume ; fadeTime = 1.0 ; // given in seconds state \"main\" { } state \"fadeout\" { music . volume -= Time . delta / fadeTime ; if ( music . volume <= 0.0 ) { music . pause (); music . volume = prevVolume ; state = \"main\" ; } } // call fadeOut() to make the // music fade smoothly fun fadeOut ( seconds ) { if ( state == \"main\" ) prevVolume = music . volume ; fadeTime = seconds ; state = \"fadeout\" ; } }","title":"Music"},{"location":"engine/music/#factory","text":"","title":"Factory"},{"location":"engine/music/#music_1","text":"Audio.Music(path) Creates a Music object associated with a certain file. Arguments path : string. The path of the music - usually a file in the musics/ folder. Returns A Music object. Example using SurgeEngine.Audio.Music ; object \"MusicTest\" { music = Music ( \"musics/options.ogg\" ); state \"main\" { // loop music if (! music . playing ) music . play (); } }","title":"Music"},{"location":"engine/music/#properties","text":"","title":"Properties"},{"location":"engine/music/#playing","text":"playing : boolean, read-only. Will be true if the music is playing.","title":"playing"},{"location":"engine/music/#volume","text":"volume : number. The volume of the music, a value between 0.0 and 1.0, inclusive (zero means silence).","title":"volume"},{"location":"engine/music/#functions","text":"","title":"Functions"},{"location":"engine/music/#play","text":"play() Plays the music (once). To make it loop, play it whenever music.playing is false .","title":"play"},{"location":"engine/music/#stop","text":"stop() Stops the music. Once the music is stopped, it can only be played again from the beginning.","title":"stop"},{"location":"engine/music/#pause","text":"pause() Pauses the music. A paused music can be resumed later with play() .","title":"pause"},{"location":"engine/platform/","text":"Platform Routines specific to the platform the game engine is currently running on. Available since : Open Surge 0.6.1 Example // Let's find out which platform the game engine is currently running on using SurgeEngine.Platform ; object \"Application\" { state \"main\" { Console . print ( platformName ()); state = \"done\" ; } state \"done\" { } fun platformName () { if ( Platform . isAndroid ) return \"Android\" ; else if ( Platform . isWindows ) return \"Windows\" ; else if ( Platform . isMacOS ) return \"macOS\" ; else if ( Platform . isUnix ) return \"Unix\" ; else return \"Unknown\" ; } } Properties isWindows isWindows : boolean, read-only. Will be true if the game engine is running on Microsoft Windows. isUnix isUnix : boolean, read-only. Will be true if the game engine is running on a Unix-like operating system such as: Linux, BSD, macOS, Android, etc. isMacOS isMacOS : boolean, read-only. Will be true if the game engine is running on macOS. isAndroid isAndroid : boolean, read-only. Will be true if the game engine is running on Android. Check SurgeEngine.mobile instead if you want to know if the game engine is running on mobile mode.","title":"Platform"},{"location":"engine/platform/#platform","text":"Routines specific to the platform the game engine is currently running on. Available since : Open Surge 0.6.1 Example // Let's find out which platform the game engine is currently running on using SurgeEngine.Platform ; object \"Application\" { state \"main\" { Console . print ( platformName ()); state = \"done\" ; } state \"done\" { } fun platformName () { if ( Platform . isAndroid ) return \"Android\" ; else if ( Platform . isWindows ) return \"Windows\" ; else if ( Platform . isMacOS ) return \"macOS\" ; else if ( Platform . isUnix ) return \"Unix\" ; else return \"Unknown\" ; } }","title":"Platform"},{"location":"engine/platform/#properties","text":"","title":"Properties"},{"location":"engine/platform/#iswindows","text":"isWindows : boolean, read-only. Will be true if the game engine is running on Microsoft Windows.","title":"isWindows"},{"location":"engine/platform/#isunix","text":"isUnix : boolean, read-only. Will be true if the game engine is running on a Unix-like operating system such as: Linux, BSD, macOS, Android, etc.","title":"isUnix"},{"location":"engine/platform/#ismacos","text":"isMacOS : boolean, read-only. Will be true if the game engine is running on macOS.","title":"isMacOS"},{"location":"engine/platform/#isandroid","text":"isAndroid : boolean, read-only. Will be true if the game engine is running on Android. Check SurgeEngine.mobile instead if you want to know if the game engine is running on mobile mode.","title":"isAndroid"},{"location":"engine/platformer/","text":"Platformer The Platformer behavior makes the associated entity perform a simple platform movement (with gravity, etc). Used mostly by NPCs and baddies, this behavior is supposed to be lightweight for the CPU and is not designed to support 360\u00b0-physics. Important: for best results, the hot spot of the entity should be placed on its feet. Example // // In the example below, we create a dummy that // walks around the level (left and right) // using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.Platformer ; object \"My Baddie\" is \"entity\" , \"enemy\" { actor = Actor ( \"My Baddie\" ); // give it graphics enemy = Enemy (); // make it behave like a baddie platformer = Platformer (); // give it a platform movement state \"main\" { platformer . speed = 60 ; // 60 pixels per second platformer . walk (); // make it walk } } Factory Behaviors.Platformer Platformer() Spawns a Platformer. Returns The behavior object. Properties speed speed : number. Walking speed, in pixels per second. jumpSpeed jumpSpeed : number. Jump speed, in pixels per second. The higher the value, the more intense the jump. gravityMultiplier gravityMultiplier : number. A multiplier used to modify how the Platformer is affected by gravity. When set to 1.0, the Platformer will subject to the default acceleration of gravity . When set to 2.0 (0.5), the Platformer will be subject to twice (half) the default gravity, and so on. Zero means no gravity. Defaults to 1.0. Available since: Open Surge 0.6.0 direction direction : number, read-only. Direction will be +1 if the platformer is facing right or -1 is it's facing left. walking walking : boolean, read-only. Is the platformer walking? walkingLeft walkingLeft : boolean, read-only. Is the platformer walking to the left? walkingRight walkingRight : boolean, read-only. Is the platformer walking to the right? midair midair : boolean, read-only. Is the platformer midair? falling falling : boolean, read-only. Is the platformer falling down? wall wall : boolean, read-only. Is the platformer touching a wall? leftWall leftWall : boolean, read-only. Is the platformer touching a wall on its left side? rightWall rightWall : boolean, read-only. Is the platformer touching a wall on its right side? leftLedge leftLedge : boolean, read-only. Is the platformer standing on a ledge located on its left side? rightLedge rightLedge : boolean, read-only. Is the platformer standing on a ledge located on its right side? Functions walk walk() Enables automatic walking. The platformer will walk left and right automatically. Returns Returns the platformer itself. walkLeft walkLeft() Makes the platformer walk to the left. Returns Returns the platformer itself. walkRight walkRight() Makes the platformer walk to the right. Returns Returns the platformer itself. stop stop() Makes the platformer stop walking. Returns Returns the platformer itself. jump jump() Makes the platformer jump. It will only jump if it's touching the ground. Returns Returns the platformer itself. Example // // In the example below, we create a jumping // dummy that walks left and right // using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.Platformer ; object \"My Jumping Baddie\" is \"entity\" , \"enemy\" { actor = Actor ( \"My Jumping Baddie\" ); // handles the graphics enemy = Enemy (); // make it behave like a baddie platformer = Platformer (). walk (); // make it walk state \"main\" { platformer . speed = 60 ; // 60 pixels per second if ( timeout ( 3.0 )) // jump every 3 seconds state = \"jump\" ; } state \"jump\" { platformer . jump (); state = \"main\" ; } } forceJump forceJump(speed) Makes the platformer jump, regardless if it's touching the ground or not. Arguments speed : number. Jump speed in pixels per second. Returns Returns the platformer itself. setSensorBox setSensorBox(width, height) The platformer spawns invisible sensors to detect collisions. Together, these sensors are thought to form a box which size is related to the size of the individual sensors. This function sets the size of this box. That size should be compatible with the size of the sprite and a size too small may break the platformer. The size of the sensor box is computed automatically, so normally you don't need to modify it. Arguments width : number. The width of the box, in pixels. height : number. The height of the box, in pixels. Returns Returns the platformer itself. showSensors showSensors() Displays the internal sensors of the platformer, which are invisible by default. For debugging only. Available since: Open Surge 0.5.2 Returns Returns the platformer itself. Example using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Platformer ; object \"Testing Stuff\" is \"entity\" { actor = Actor ( \"Testing Stuff\" ); platformer = Platformer (). showSensors (); // ... } hideSensors hideSensors() Hides the internal sensors of the platformer. This is the default. Available since: Open Surge 0.5.2 Returns Returns the platformer itself.","title":"Platformer"},{"location":"engine/platformer/#platformer","text":"The Platformer behavior makes the associated entity perform a simple platform movement (with gravity, etc). Used mostly by NPCs and baddies, this behavior is supposed to be lightweight for the CPU and is not designed to support 360\u00b0-physics. Important: for best results, the hot spot of the entity should be placed on its feet. Example // // In the example below, we create a dummy that // walks around the level (left and right) // using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.Platformer ; object \"My Baddie\" is \"entity\" , \"enemy\" { actor = Actor ( \"My Baddie\" ); // give it graphics enemy = Enemy (); // make it behave like a baddie platformer = Platformer (); // give it a platform movement state \"main\" { platformer . speed = 60 ; // 60 pixels per second platformer . walk (); // make it walk } }","title":"Platformer"},{"location":"engine/platformer/#factory","text":"","title":"Factory"},{"location":"engine/platformer/#behaviorsplatformer","text":"Platformer() Spawns a Platformer. Returns The behavior object.","title":"Behaviors.Platformer"},{"location":"engine/platformer/#properties","text":"","title":"Properties"},{"location":"engine/platformer/#speed","text":"speed : number. Walking speed, in pixels per second.","title":"speed"},{"location":"engine/platformer/#jumpspeed","text":"jumpSpeed : number. Jump speed, in pixels per second. The higher the value, the more intense the jump.","title":"jumpSpeed"},{"location":"engine/platformer/#gravitymultiplier","text":"gravityMultiplier : number. A multiplier used to modify how the Platformer is affected by gravity. When set to 1.0, the Platformer will subject to the default acceleration of gravity . When set to 2.0 (0.5), the Platformer will be subject to twice (half) the default gravity, and so on. Zero means no gravity. Defaults to 1.0. Available since: Open Surge 0.6.0","title":"gravityMultiplier"},{"location":"engine/platformer/#direction","text":"direction : number, read-only. Direction will be +1 if the platformer is facing right or -1 is it's facing left.","title":"direction"},{"location":"engine/platformer/#walking","text":"walking : boolean, read-only. Is the platformer walking?","title":"walking"},{"location":"engine/platformer/#walkingleft","text":"walkingLeft : boolean, read-only. Is the platformer walking to the left?","title":"walkingLeft"},{"location":"engine/platformer/#walkingright","text":"walkingRight : boolean, read-only. Is the platformer walking to the right?","title":"walkingRight"},{"location":"engine/platformer/#midair","text":"midair : boolean, read-only. Is the platformer midair?","title":"midair"},{"location":"engine/platformer/#falling","text":"falling : boolean, read-only. Is the platformer falling down?","title":"falling"},{"location":"engine/platformer/#wall","text":"wall : boolean, read-only. Is the platformer touching a wall?","title":"wall"},{"location":"engine/platformer/#leftwall","text":"leftWall : boolean, read-only. Is the platformer touching a wall on its left side?","title":"leftWall"},{"location":"engine/platformer/#rightwall","text":"rightWall : boolean, read-only. Is the platformer touching a wall on its right side?","title":"rightWall"},{"location":"engine/platformer/#leftledge","text":"leftLedge : boolean, read-only. Is the platformer standing on a ledge located on its left side?","title":"leftLedge"},{"location":"engine/platformer/#rightledge","text":"rightLedge : boolean, read-only. Is the platformer standing on a ledge located on its right side?","title":"rightLedge"},{"location":"engine/platformer/#functions","text":"","title":"Functions"},{"location":"engine/platformer/#walk","text":"walk() Enables automatic walking. The platformer will walk left and right automatically. Returns Returns the platformer itself.","title":"walk"},{"location":"engine/platformer/#walkleft","text":"walkLeft() Makes the platformer walk to the left. Returns Returns the platformer itself.","title":"walkLeft"},{"location":"engine/platformer/#walkright","text":"walkRight() Makes the platformer walk to the right. Returns Returns the platformer itself.","title":"walkRight"},{"location":"engine/platformer/#stop","text":"stop() Makes the platformer stop walking. Returns Returns the platformer itself.","title":"stop"},{"location":"engine/platformer/#jump","text":"jump() Makes the platformer jump. It will only jump if it's touching the ground. Returns Returns the platformer itself. Example // // In the example below, we create a jumping // dummy that walks left and right // using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.Platformer ; object \"My Jumping Baddie\" is \"entity\" , \"enemy\" { actor = Actor ( \"My Jumping Baddie\" ); // handles the graphics enemy = Enemy (); // make it behave like a baddie platformer = Platformer (). walk (); // make it walk state \"main\" { platformer . speed = 60 ; // 60 pixels per second if ( timeout ( 3.0 )) // jump every 3 seconds state = \"jump\" ; } state \"jump\" { platformer . jump (); state = \"main\" ; } }","title":"jump"},{"location":"engine/platformer/#forcejump","text":"forceJump(speed) Makes the platformer jump, regardless if it's touching the ground or not. Arguments speed : number. Jump speed in pixels per second. Returns Returns the platformer itself.","title":"forceJump"},{"location":"engine/platformer/#setsensorbox","text":"setSensorBox(width, height) The platformer spawns invisible sensors to detect collisions. Together, these sensors are thought to form a box which size is related to the size of the individual sensors. This function sets the size of this box. That size should be compatible with the size of the sprite and a size too small may break the platformer. The size of the sensor box is computed automatically, so normally you don't need to modify it. Arguments width : number. The width of the box, in pixels. height : number. The height of the box, in pixels. Returns Returns the platformer itself.","title":"setSensorBox"},{"location":"engine/platformer/#showsensors","text":"showSensors() Displays the internal sensors of the platformer, which are invisible by default. For debugging only. Available since: Open Surge 0.5.2 Returns Returns the platformer itself. Example using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Platformer ; object \"Testing Stuff\" is \"entity\" { actor = Actor ( \"Testing Stuff\" ); platformer = Platformer (). showSensors (); // ... }","title":"showSensors"},{"location":"engine/platformer/#hidesensors","text":"hideSensors() Hides the internal sensors of the platformer. This is the default. Available since: Open Surge 0.5.2 Returns Returns the platformer itself.","title":"hideSensors"},{"location":"engine/player/","text":"Player The Player object is used to control a specific player/character. Player objects are tagged player . Note: in Open Surge, companion objects can be used to give new abilities to players. Companion objects must be indicated in the character definition files (.chr) and are implemented as regular scripts. The engine will automatically spawn the companions as children of the appropriate Player objects. Example object \"Display player name\" is \"companion\" { player = parent ; // since this object is configured as a // companion, parent is the reference // to the appropriate Player object state \"main\" { Console . print ( \"I am a companion of \" + player . name ); } } Global Player Player(playerName) Gets the Player object associated with a character in the level. If a player with the specified name doesn't exist in the level, there will be an error. See also: exists . Arguments playerName : string. The name of a character, as defined in a .chr file stored in the characters/ folder. Returns A Player object. Example using SurgeEngine.Player ; // Gives Surge 1 collectible each second // Just place it in your level object \"Collectible Giver\" is \"entity\" , \"awake\" { player = Player ( \"Surge\" ); state \"main\" { if ( timeout ( 1 )) state = \"give collectible\" ; } state \"give collectible\" { player . collectibles = player . collectibles + 1 ; state = \"main\" ; } } Player.get Player[i] Gets a Player object by its sequence number, as defined in the players entry of the level file. See also: count . Arguments i : number. An integer between 0 and Player.count - 1 , inclusive. Returns A Player object. Player.exists Player.exists(playerName) Checks if a player named playerName exists in the level. Arguments playerName : string. The name of a character. Returns Returns true if such a player exists in the level. Player.active Player.active : Player object. The player currently in focus. See also: focus , hasFocus , focusable . Example using SurgeEngine.Player ; // Tells the name of the active player // Just place it in the level object \"Who am I\" is \"entity\" , \"awake\" { state \"main\" { player = Player . active ; Console . print ( \"I am \" + player . name ); destroy (); } } Player.count Player.count : number, read-only. The number of players in the level. Player.initialLives Player.initialLives : number, read-only. The initial number of lives set by the engine. Properties id id : number, read-only. A number that uniquely identifies the player in the Level. See also: name . Available since: Open Surge 0.6.1 name name : string, read-only. The name of the character. See also: id . direction direction : number, read-only. This number will be +1 if the player is facing right, or -1 if facing left. See also: hflip . Example // let's check if the player is facing right or left isFacingRight = ( player . direction > 0 ); isFacingLeft = ( player . direction < 0 ); input input : Input object, read-only. Reference to the Input object of the Player. Example using SurgeEngine.Player ; object \"Application\" { state \"main\" { player = Player . active ; if ( player . input . buttonDown ( \"right\" )) Console . print ( \"Player is holding right\" ); } } animation animation : Animation object, read-only. Reference to the Animation object of the Player. See also: anim . anim anim : number. A shortcut to animation.id : an integer corresponding to the current animation number. See also: animation , id . anchor anchor : Vector2 object. A shortcut to animation.anchor . See also: anchor . Available since: Open Surge 0.6.0 hotSpot hotSpot : Vector2 object. A shortcut to animation.hotSpot . See also: hotSpot . Available since: Open Surge 0.6.0. Note: in versions prior to 0.6.0, you may get the hot spot using the Animation object. actionSpot actionSpot : Vector2 object. A shortcut to animation.actionSpot . See also: actionSpot . Available since: Open Surge 0.6.0 actionOffset actionOffset : Vector2 object, read-only. A shortcut to animation.actionOffset . See also: actionOffset . Available since: Open Surge 0.6.0 attacking attacking : boolean, read-only. Is the player attacking, i.e., jumping, rolling, charging or invincible? This flag will be modified if the player is aggressive or inoffensive. See also: aggressive , inoffensive . midair midair : boolean, read-only. Is the player midair? stopped stopped : boolean, read-only. Is the player stopped? walking walking : boolean, read-only. Is the player walking? running running : boolean, read-only. Is the player running? jumping jumping : boolean, read-only. Is the player jumping? springing springing : boolean, read-only. Is the player playing the \"springing\" animation, displayed just after hitting a spring? braking braking : boolean, read-only. Is the player braking? balancing balancing : boolean, read-only. Is the player balancing on a ledge? waiting waiting : boolean, read-only. Is the player waiting? (happens after remaining stopped for a few seconds) rolling rolling : boolean, read-only. Is the player rolling? charging charging : boolean, read-only. Is the player charging a rolling movement? pushing pushing : boolean, read-only. Is the player pushing a wall? hit hit : boolean, read-only. Is the player getting hit (i.e., losing collectibles or a shield)? See also: getHit . blinking blinking : boolean, read-only. Is the player blinking? (happens just after getting hit) dying dying : boolean, read-only. Is the player dying or drowning? drowning drowning : boolean, read-only. Is the player drowning (i.e., dying underwater)? See also: underwater , dying . breathing breathing : boolean, read-only. Is the player breathing an air bubble that is underwater? See also: underwater , breathTime . crouchingDown crouchingDown : boolean, read-only. Is the player crouching down? lookingUp lookingUp : boolean, read-only. Is the player looking up? winning winning : boolean, read-only. Is the player displaying the \"winning\" animation (after clearing a level)? underwater underwater : boolean, read-only. Is the player underwater? Players are considered to be underwater if they are below the water level or if their forciblyUnderwater flag is set to true . See also: secondsToDrown , drowning , breathing , breathTime , forciblyUnderwater , forciblyOutOfWater , waterlevel . secondsToDrown secondsToDrown : number, read-only. The number of seconds to drown, if underwater. See also: underwater , drowning , breathTime . topspeed topspeed : number, read-only. The maximum speed that the player can reach when running naturally, without rolling and with no external forces applied. Given in pixels per second. See also: capspeed . capspeed capspeed : number, read-only. The maximum speed that the player can reach by normal means (e.g., rolling downhill), not considering external forces. Given in pixels per second. See also: topspeed . Available since: Open Surge 0.6.1 hlockTime hlockTime : number, read-only. The time, in seconds, in which the player will not respond to horizontal input when on the ground. Defaults to zero. See also: hlock . Available since: Open Surge 0.6.1 transform transform : Transform object, read-only. The transform of the Player. collider collider : Collider object, read-only. A collider associated with this Player. shield shield : string | null . One of the following: \"shield\" , \"fire\" , \"thunder\" , \"water\" , \"acid\" , \"wind\" or null (if there is no shield). See also: invulnerable . invincible invincible : boolean. Used to make the player invincible. Defaults to false . turbo turbo : boolean. Turbocharged mode (increases player speed). Defaults to false . frozen frozen : boolean. Disable/enable player movement. Defaults to false . aggressive aggressive : boolean. If set to true , the attacking flag will be true regardless of the state of the player. The player will be able to hit the baddies just by touching them. Defaults to false . See also: attacking , inoffensive . Available since: Open Surge 0.5.1 inoffensive inoffensive : boolean. If set to true , the attacking flag will be false regardless of the state of the player. The player will be vulnerable to damage even if jumping, rolling or charging. Defaults to false . Note: if the player is simultaneously aggressive and inoffensive, the aggressive behavior prevails. See also: attacking , aggressive . Available since: Open Surge 0.6.1 invulnerable invulnerable : boolean. If set to true , the player will be invulnerable to damage. It's like having an invisible shield that is permanent. The player may still be killed if crushed, by falling into a pit, by drowning, or by calling kill . Available since: Open Surge 0.6.1 immortal immortal : boolean. If an immortal player appears to be killed, it will appear to be ressurrected on its spawn point without losing a life . See also: lives . Available since: Open Surge 0.6.1 secondary secondary : boolean. A secondary player plays a secondary role and interacts with items in different ways. It cannot smash item boxes, activate goal signs, etc. This flag is best used with AI-controlled players. Defaults to false . Available since: Open Surge 0.6.1 focusable focusable : boolean. A focusable player can receive focus. Defaults to true . See also: focus , hasFocus , Player.active . Available since: Open Surge 0.6.1 Note: if only a single player exists in the level, then that player will have focus regardless of the value of this flag. breathTime breathTime : number. The maximum number of seconds the player can remain underwater without breathing. See also: underwater , secondsToDrown . forciblyUnderwater forciblyUnderwater : boolean. If set to true , the underwater flag will be true regardless of the water level . If set to false , the underwater flag will be true only if the player is below the water level. Defaults to false . See also: underwater , waterlevel , forciblyOutOfWater . Available since: Open Surge 0.6.1 forciblyOutOfWater If set to true , the underwater mechanics will be disabled, even if the player is below the water level . If forciblyUnderwater is also true , this flag will do nothing. Defaults to false . See also: underwater , waterlevel , forciblyUnderwater . Available since: Open Surge 0.6.1 layer layer : string. The current layer of the player. One of the following: \"green\" , \"yellow\" , \"default\" . This property tells you which bricks will be sensed, depending on their layer. visible visible : boolean. Should the player sprite be rendered? Defaults to true . collectibles collectibles : number. The number of collectibles, an integer shared between all player objects. lives lives : number. The number of lives, an integer shared between all player objects. score score : number. The score of the player, an integer value shared between all player objects. speed speed : number. The speed of the player, in pixels per second. This will be mapped automatically to gsp or xsp , depending on whether the player is touching the ground or not. See also: gsp , xsp . gsp gsp : number. Ground speed, in pixels per second. Prefer using speed instead, since gsp is only meaningful if the player is touching the ground. See also: speed . xsp xsp : number. Horizontal speed, in pixels per second (useful while midair). Prefer using speed instead. See also: speed . ysp ysp : number. Vertical speed, in pixels per second. angle angle : number. The angle of the player, in degrees. The same as transform.angle . See also: slope , transform . slope slope : number, read-only. The angle detected by the physics system, in degrees. Unlike angle , slope is read-only and does not feature any smoothing for visual aesthetics. Its purpose is to be a helper for physics calculations. See also: angle . Available since: Open Surge 0.5.2 width width : number, read-only. The width of the player sprite, in pixels. See also: height . height height : number, read-only. The height of the player sprite, in pixels. See also: width . hflip hflip : boolean. Used to horizontally flip the sprite of the player relative to its direction . Defaults to false . Changing this flag does not change the direction of the player in any way. It only changes the way the sprite is rendered. Also, reading this flag alone does not tell you whether the sprite is facing left or right. Use it in addition to the direction of the player for that. See also: direction , vflip . Available since: Open Surge 0.6.1 Example // make the sprite appear in accordance with player.direction player . hflip = false ; // make the sprite appear flipped relative to player.direction player . hflip = true ; // make the sprite appear facing right, regardless of player.direction player . hflip = ( player . direction < 0 ); // make the sprite appear facing left, regardless of player.direction player . hflip = ( player . direction > 0 ); // spriteDirection is analogous to player.direction spriteDirection = player . direction * ( player . hflip ? - 1 : 1 ); // let's check if the sprite is facing right or left isFacingRight = ( spriteDirection > 0 ); isFacingLeft = ( spriteDirection < 0 ); vflip vflip : boolean. Used to vertically flip the sprite of the player. Defaults to false . See also: hflip . Available since: Open Surge 0.6.1 Functions bounce bounce(hazard | null) Makes the player bounce after smashing a hazard. The trajectory of the movement will be computed according to the position of the hazard. If no hazard is present, you may pass null as the argument. Arguments hazard : Actor object. The hazard. Example using SurgeEngine.Player ; using SurgeEngine.Actor ; using SurgeEngine.Collisions.CollisionBox ; object \"Shield Box\" is \"entity\" { actor = Actor ( \"Shield Box\" ); shieldCollider = CollisionBox ( 32 , 32 ); state \"main\" { player = Player . active ; if ( player . attacking ) { if ( player . collider . collidesWith ( shieldCollider )) { if ( player . midair ) player . bounce ( actor ); player . shield = \"fire\" ; destroy (); } } } } bounceBack bounceBack(hazard) Makes the player bounce after smashing a hazard. If the player comes at the hazard from below, the player is thrown downwards. If not, the player is thrown upwards. The hazard parameter is mandatory. Arguments hazard : Actor object. The hazard. getHit getHit(hazard | null) Makes the player get hit. Call it whenever the player gets hit by a hazard. The hit movement will be calculated according to the position of the hazard. If no hazard is present, you may pass null as the argument. Arguments hazard : Actor object. The hazard. See also: hit . kill kill() Kills the player. breathe breathe() Makes the player breathe (underwater only). restore restore() Restores the player to a vulnerable state. Available since: Open Surge 0.6.1 springify springify() Activates the \"springing\" activity. See also: restore . roll roll() Makes the player roll. hlock hlock(seconds) Locks the horizontal controls of the player for the specified time. Left and right input will be ignored during that time. See also: hlockTime . Arguments seconds : number. How long the horizontal controls of the player will stay locked? This usually should be set to a value no higher than 0.5 . Note: since Open Surge 0.6.1, the locking will not take place if the player is midair. focus focus() Focuses on the player. The focused player is controlled by the user. Only one player has focus at any given time. See also: hasFocus , focusable , Player.active . Returns Returns true on success, false otherwise. hasFocus hasFocus() Does the player have focus? See also: focus , focusable , Player.active . Returns Returns true if the player has focus, false otherwise. moveBy moveBy(dx, dy) Moves the player by a ( dx , dy ) offset after the physics update of the current framestep. This is similar to calling player.transform.translateBy(dx, dy) in lateUpdate() . See also: lateUpdate , translateBy . Available since: Open Surge 0.6.1 Arguments dx : number. Horizontal offset in pixels. dy : number. Vertical offset in pixels. Example // Let's compare player.moveBy() to // player.transform.translateBy() dx = 5 ; dy = 0 ; // this moves the player AFTER the physics update player . moveBy ( dx , dy ); // this moves the player BEFORE the physics update // (immediately), unless you call it in lateUpdate() player . transform . translateBy ( dx , dy ); move move(offset) Moves the player by the given offset after the physics update of the current framestep. Calling player.move(offset) is equivalent to calling player.moveBy(offset.x, offset.y) . See also: moveBy . Available since: Open Surge 0.6.1 Arguments offset : Vector2 object. Offset vector. transformInto player.transformInto(characterName) Transforms the player into the character named characterName . The transformation succeeds only if there is such a character. Available since: Open Surge 0.6.1 Arguments characterName : string. The name of a character, as defined in a .chr file. Returns Returns true if the transformation is successful. Transforming a player into itself is considered successful, but nothing happens in this case. // this player will become Surge player . transformInto ( \"Surge\" ); // this player will become Tux player . transformInto ( \"Tux\" ); // the following transformation will fail: if (! player . transformInto ( \"non-existent-character\" )) Console . print ( \"No transformation took place!\" ); // After a successful transformation: // - player.name will change; // - player.id will not change!","title":"Player"},{"location":"engine/player/#player","text":"The Player object is used to control a specific player/character. Player objects are tagged player . Note: in Open Surge, companion objects can be used to give new abilities to players. Companion objects must be indicated in the character definition files (.chr) and are implemented as regular scripts. The engine will automatically spawn the companions as children of the appropriate Player objects. Example object \"Display player name\" is \"companion\" { player = parent ; // since this object is configured as a // companion, parent is the reference // to the appropriate Player object state \"main\" { Console . print ( \"I am a companion of \" + player . name ); } }","title":"Player"},{"location":"engine/player/#global","text":"","title":"Global"},{"location":"engine/player/#player_1","text":"Player(playerName) Gets the Player object associated with a character in the level. If a player with the specified name doesn't exist in the level, there will be an error. See also: exists . Arguments playerName : string. The name of a character, as defined in a .chr file stored in the characters/ folder. Returns A Player object. Example using SurgeEngine.Player ; // Gives Surge 1 collectible each second // Just place it in your level object \"Collectible Giver\" is \"entity\" , \"awake\" { player = Player ( \"Surge\" ); state \"main\" { if ( timeout ( 1 )) state = \"give collectible\" ; } state \"give collectible\" { player . collectibles = player . collectibles + 1 ; state = \"main\" ; } }","title":"Player"},{"location":"engine/player/#playerget","text":"Player[i] Gets a Player object by its sequence number, as defined in the players entry of the level file. See also: count . Arguments i : number. An integer between 0 and Player.count - 1 , inclusive. Returns A Player object.","title":"Player.get"},{"location":"engine/player/#playerexists","text":"Player.exists(playerName) Checks if a player named playerName exists in the level. Arguments playerName : string. The name of a character. Returns Returns true if such a player exists in the level.","title":"Player.exists"},{"location":"engine/player/#playeractive","text":"Player.active : Player object. The player currently in focus. See also: focus , hasFocus , focusable . Example using SurgeEngine.Player ; // Tells the name of the active player // Just place it in the level object \"Who am I\" is \"entity\" , \"awake\" { state \"main\" { player = Player . active ; Console . print ( \"I am \" + player . name ); destroy (); } }","title":"Player.active"},{"location":"engine/player/#playercount","text":"Player.count : number, read-only. The number of players in the level.","title":"Player.count"},{"location":"engine/player/#playerinitiallives","text":"Player.initialLives : number, read-only. The initial number of lives set by the engine.","title":"Player.initialLives"},{"location":"engine/player/#properties","text":"","title":"Properties"},{"location":"engine/player/#id","text":"id : number, read-only. A number that uniquely identifies the player in the Level. See also: name . Available since: Open Surge 0.6.1","title":"id"},{"location":"engine/player/#name","text":"name : string, read-only. The name of the character. See also: id .","title":"name"},{"location":"engine/player/#direction","text":"direction : number, read-only. This number will be +1 if the player is facing right, or -1 if facing left. See also: hflip . Example // let's check if the player is facing right or left isFacingRight = ( player . direction > 0 ); isFacingLeft = ( player . direction < 0 );","title":"direction"},{"location":"engine/player/#input","text":"input : Input object, read-only. Reference to the Input object of the Player. Example using SurgeEngine.Player ; object \"Application\" { state \"main\" { player = Player . active ; if ( player . input . buttonDown ( \"right\" )) Console . print ( \"Player is holding right\" ); } }","title":"input"},{"location":"engine/player/#animation","text":"animation : Animation object, read-only. Reference to the Animation object of the Player. See also: anim .","title":"animation"},{"location":"engine/player/#anim","text":"anim : number. A shortcut to animation.id : an integer corresponding to the current animation number. See also: animation , id .","title":"anim"},{"location":"engine/player/#anchor","text":"anchor : Vector2 object. A shortcut to animation.anchor . See also: anchor . Available since: Open Surge 0.6.0","title":"anchor"},{"location":"engine/player/#hotspot","text":"hotSpot : Vector2 object. A shortcut to animation.hotSpot . See also: hotSpot . Available since: Open Surge 0.6.0. Note: in versions prior to 0.6.0, you may get the hot spot using the Animation object.","title":"hotSpot"},{"location":"engine/player/#actionspot","text":"actionSpot : Vector2 object. A shortcut to animation.actionSpot . See also: actionSpot . Available since: Open Surge 0.6.0","title":"actionSpot"},{"location":"engine/player/#actionoffset","text":"actionOffset : Vector2 object, read-only. A shortcut to animation.actionOffset . See also: actionOffset . Available since: Open Surge 0.6.0","title":"actionOffset"},{"location":"engine/player/#attacking","text":"attacking : boolean, read-only. Is the player attacking, i.e., jumping, rolling, charging or invincible? This flag will be modified if the player is aggressive or inoffensive. See also: aggressive , inoffensive .","title":"attacking"},{"location":"engine/player/#midair","text":"midair : boolean, read-only. Is the player midair?","title":"midair"},{"location":"engine/player/#stopped","text":"stopped : boolean, read-only. Is the player stopped?","title":"stopped"},{"location":"engine/player/#walking","text":"walking : boolean, read-only. Is the player walking?","title":"walking"},{"location":"engine/player/#running","text":"running : boolean, read-only. Is the player running?","title":"running"},{"location":"engine/player/#jumping","text":"jumping : boolean, read-only. Is the player jumping?","title":"jumping"},{"location":"engine/player/#springing","text":"springing : boolean, read-only. Is the player playing the \"springing\" animation, displayed just after hitting a spring?","title":"springing"},{"location":"engine/player/#braking","text":"braking : boolean, read-only. Is the player braking?","title":"braking"},{"location":"engine/player/#balancing","text":"balancing : boolean, read-only. Is the player balancing on a ledge?","title":"balancing"},{"location":"engine/player/#waiting","text":"waiting : boolean, read-only. Is the player waiting? (happens after remaining stopped for a few seconds)","title":"waiting"},{"location":"engine/player/#rolling","text":"rolling : boolean, read-only. Is the player rolling?","title":"rolling"},{"location":"engine/player/#charging","text":"charging : boolean, read-only. Is the player charging a rolling movement?","title":"charging"},{"location":"engine/player/#pushing","text":"pushing : boolean, read-only. Is the player pushing a wall?","title":"pushing"},{"location":"engine/player/#hit","text":"hit : boolean, read-only. Is the player getting hit (i.e., losing collectibles or a shield)? See also: getHit .","title":"hit"},{"location":"engine/player/#blinking","text":"blinking : boolean, read-only. Is the player blinking? (happens just after getting hit)","title":"blinking"},{"location":"engine/player/#dying","text":"dying : boolean, read-only. Is the player dying or drowning?","title":"dying"},{"location":"engine/player/#drowning","text":"drowning : boolean, read-only. Is the player drowning (i.e., dying underwater)? See also: underwater , dying .","title":"drowning"},{"location":"engine/player/#breathing","text":"breathing : boolean, read-only. Is the player breathing an air bubble that is underwater? See also: underwater , breathTime .","title":"breathing"},{"location":"engine/player/#crouchingdown","text":"crouchingDown : boolean, read-only. Is the player crouching down?","title":"crouchingDown"},{"location":"engine/player/#lookingup","text":"lookingUp : boolean, read-only. Is the player looking up?","title":"lookingUp"},{"location":"engine/player/#winning","text":"winning : boolean, read-only. Is the player displaying the \"winning\" animation (after clearing a level)?","title":"winning"},{"location":"engine/player/#underwater","text":"underwater : boolean, read-only. Is the player underwater? Players are considered to be underwater if they are below the water level or if their forciblyUnderwater flag is set to true . See also: secondsToDrown , drowning , breathing , breathTime , forciblyUnderwater , forciblyOutOfWater , waterlevel .","title":"underwater"},{"location":"engine/player/#secondstodrown","text":"secondsToDrown : number, read-only. The number of seconds to drown, if underwater. See also: underwater , drowning , breathTime .","title":"secondsToDrown"},{"location":"engine/player/#topspeed","text":"topspeed : number, read-only. The maximum speed that the player can reach when running naturally, without rolling and with no external forces applied. Given in pixels per second. See also: capspeed .","title":"topspeed"},{"location":"engine/player/#capspeed","text":"capspeed : number, read-only. The maximum speed that the player can reach by normal means (e.g., rolling downhill), not considering external forces. Given in pixels per second. See also: topspeed . Available since: Open Surge 0.6.1","title":"capspeed"},{"location":"engine/player/#hlocktime","text":"hlockTime : number, read-only. The time, in seconds, in which the player will not respond to horizontal input when on the ground. Defaults to zero. See also: hlock . Available since: Open Surge 0.6.1","title":"hlockTime"},{"location":"engine/player/#transform","text":"transform : Transform object, read-only. The transform of the Player.","title":"transform"},{"location":"engine/player/#collider","text":"collider : Collider object, read-only. A collider associated with this Player.","title":"collider"},{"location":"engine/player/#shield","text":"shield : string | null . One of the following: \"shield\" , \"fire\" , \"thunder\" , \"water\" , \"acid\" , \"wind\" or null (if there is no shield). See also: invulnerable .","title":"shield"},{"location":"engine/player/#invincible","text":"invincible : boolean. Used to make the player invincible. Defaults to false .","title":"invincible"},{"location":"engine/player/#turbo","text":"turbo : boolean. Turbocharged mode (increases player speed). Defaults to false .","title":"turbo"},{"location":"engine/player/#frozen","text":"frozen : boolean. Disable/enable player movement. Defaults to false .","title":"frozen"},{"location":"engine/player/#aggressive","text":"aggressive : boolean. If set to true , the attacking flag will be true regardless of the state of the player. The player will be able to hit the baddies just by touching them. Defaults to false . See also: attacking , inoffensive . Available since: Open Surge 0.5.1","title":"aggressive"},{"location":"engine/player/#inoffensive","text":"inoffensive : boolean. If set to true , the attacking flag will be false regardless of the state of the player. The player will be vulnerable to damage even if jumping, rolling or charging. Defaults to false . Note: if the player is simultaneously aggressive and inoffensive, the aggressive behavior prevails. See also: attacking , aggressive . Available since: Open Surge 0.6.1","title":"inoffensive"},{"location":"engine/player/#invulnerable","text":"invulnerable : boolean. If set to true , the player will be invulnerable to damage. It's like having an invisible shield that is permanent. The player may still be killed if crushed, by falling into a pit, by drowning, or by calling kill . Available since: Open Surge 0.6.1","title":"invulnerable"},{"location":"engine/player/#immortal","text":"immortal : boolean. If an immortal player appears to be killed, it will appear to be ressurrected on its spawn point without losing a life . See also: lives . Available since: Open Surge 0.6.1","title":"immortal"},{"location":"engine/player/#secondary","text":"secondary : boolean. A secondary player plays a secondary role and interacts with items in different ways. It cannot smash item boxes, activate goal signs, etc. This flag is best used with AI-controlled players. Defaults to false . Available since: Open Surge 0.6.1","title":"secondary"},{"location":"engine/player/#focusable","text":"focusable : boolean. A focusable player can receive focus. Defaults to true . See also: focus , hasFocus , Player.active . Available since: Open Surge 0.6.1 Note: if only a single player exists in the level, then that player will have focus regardless of the value of this flag.","title":"focusable"},{"location":"engine/player/#breathtime","text":"breathTime : number. The maximum number of seconds the player can remain underwater without breathing. See also: underwater , secondsToDrown .","title":"breathTime"},{"location":"engine/player/#forciblyunderwater","text":"forciblyUnderwater : boolean. If set to true , the underwater flag will be true regardless of the water level . If set to false , the underwater flag will be true only if the player is below the water level. Defaults to false . See also: underwater , waterlevel , forciblyOutOfWater . Available since: Open Surge 0.6.1","title":"forciblyUnderwater"},{"location":"engine/player/#forciblyoutofwater","text":"If set to true , the underwater mechanics will be disabled, even if the player is below the water level . If forciblyUnderwater is also true , this flag will do nothing. Defaults to false . See also: underwater , waterlevel , forciblyUnderwater . Available since: Open Surge 0.6.1","title":"forciblyOutOfWater"},{"location":"engine/player/#layer","text":"layer : string. The current layer of the player. One of the following: \"green\" , \"yellow\" , \"default\" . This property tells you which bricks will be sensed, depending on their layer.","title":"layer"},{"location":"engine/player/#visible","text":"visible : boolean. Should the player sprite be rendered? Defaults to true .","title":"visible"},{"location":"engine/player/#collectibles","text":"collectibles : number. The number of collectibles, an integer shared between all player objects.","title":"collectibles"},{"location":"engine/player/#lives","text":"lives : number. The number of lives, an integer shared between all player objects.","title":"lives"},{"location":"engine/player/#score","text":"score : number. The score of the player, an integer value shared between all player objects.","title":"score"},{"location":"engine/player/#speed","text":"speed : number. The speed of the player, in pixels per second. This will be mapped automatically to gsp or xsp , depending on whether the player is touching the ground or not. See also: gsp , xsp .","title":"speed"},{"location":"engine/player/#gsp","text":"gsp : number. Ground speed, in pixels per second. Prefer using speed instead, since gsp is only meaningful if the player is touching the ground. See also: speed .","title":"gsp"},{"location":"engine/player/#xsp","text":"xsp : number. Horizontal speed, in pixels per second (useful while midair). Prefer using speed instead. See also: speed .","title":"xsp"},{"location":"engine/player/#ysp","text":"ysp : number. Vertical speed, in pixels per second.","title":"ysp"},{"location":"engine/player/#angle","text":"angle : number. The angle of the player, in degrees. The same as transform.angle . See also: slope , transform .","title":"angle"},{"location":"engine/player/#slope","text":"slope : number, read-only. The angle detected by the physics system, in degrees. Unlike angle , slope is read-only and does not feature any smoothing for visual aesthetics. Its purpose is to be a helper for physics calculations. See also: angle . Available since: Open Surge 0.5.2","title":"slope"},{"location":"engine/player/#width","text":"width : number, read-only. The width of the player sprite, in pixels. See also: height .","title":"width"},{"location":"engine/player/#height","text":"height : number, read-only. The height of the player sprite, in pixels. See also: width .","title":"height"},{"location":"engine/player/#hflip","text":"hflip : boolean. Used to horizontally flip the sprite of the player relative to its direction . Defaults to false . Changing this flag does not change the direction of the player in any way. It only changes the way the sprite is rendered. Also, reading this flag alone does not tell you whether the sprite is facing left or right. Use it in addition to the direction of the player for that. See also: direction , vflip . Available since: Open Surge 0.6.1 Example // make the sprite appear in accordance with player.direction player . hflip = false ; // make the sprite appear flipped relative to player.direction player . hflip = true ; // make the sprite appear facing right, regardless of player.direction player . hflip = ( player . direction < 0 ); // make the sprite appear facing left, regardless of player.direction player . hflip = ( player . direction > 0 ); // spriteDirection is analogous to player.direction spriteDirection = player . direction * ( player . hflip ? - 1 : 1 ); // let's check if the sprite is facing right or left isFacingRight = ( spriteDirection > 0 ); isFacingLeft = ( spriteDirection < 0 );","title":"hflip"},{"location":"engine/player/#vflip","text":"vflip : boolean. Used to vertically flip the sprite of the player. Defaults to false . See also: hflip . Available since: Open Surge 0.6.1","title":"vflip"},{"location":"engine/player/#functions","text":"","title":"Functions"},{"location":"engine/player/#bounce","text":"bounce(hazard | null) Makes the player bounce after smashing a hazard. The trajectory of the movement will be computed according to the position of the hazard. If no hazard is present, you may pass null as the argument. Arguments hazard : Actor object. The hazard. Example using SurgeEngine.Player ; using SurgeEngine.Actor ; using SurgeEngine.Collisions.CollisionBox ; object \"Shield Box\" is \"entity\" { actor = Actor ( \"Shield Box\" ); shieldCollider = CollisionBox ( 32 , 32 ); state \"main\" { player = Player . active ; if ( player . attacking ) { if ( player . collider . collidesWith ( shieldCollider )) { if ( player . midair ) player . bounce ( actor ); player . shield = \"fire\" ; destroy (); } } } }","title":"bounce"},{"location":"engine/player/#bounceback","text":"bounceBack(hazard) Makes the player bounce after smashing a hazard. If the player comes at the hazard from below, the player is thrown downwards. If not, the player is thrown upwards. The hazard parameter is mandatory. Arguments hazard : Actor object. The hazard.","title":"bounceBack"},{"location":"engine/player/#gethit","text":"getHit(hazard | null) Makes the player get hit. Call it whenever the player gets hit by a hazard. The hit movement will be calculated according to the position of the hazard. If no hazard is present, you may pass null as the argument. Arguments hazard : Actor object. The hazard. See also: hit .","title":"getHit"},{"location":"engine/player/#kill","text":"kill() Kills the player.","title":"kill"},{"location":"engine/player/#breathe","text":"breathe() Makes the player breathe (underwater only).","title":"breathe"},{"location":"engine/player/#restore","text":"restore() Restores the player to a vulnerable state. Available since: Open Surge 0.6.1","title":"restore"},{"location":"engine/player/#springify","text":"springify() Activates the \"springing\" activity. See also: restore .","title":"springify"},{"location":"engine/player/#roll","text":"roll() Makes the player roll.","title":"roll"},{"location":"engine/player/#hlock","text":"hlock(seconds) Locks the horizontal controls of the player for the specified time. Left and right input will be ignored during that time. See also: hlockTime . Arguments seconds : number. How long the horizontal controls of the player will stay locked? This usually should be set to a value no higher than 0.5 . Note: since Open Surge 0.6.1, the locking will not take place if the player is midair.","title":"hlock"},{"location":"engine/player/#focus","text":"focus() Focuses on the player. The focused player is controlled by the user. Only one player has focus at any given time. See also: hasFocus , focusable , Player.active . Returns Returns true on success, false otherwise.","title":"focus"},{"location":"engine/player/#hasfocus","text":"hasFocus() Does the player have focus? See also: focus , focusable , Player.active . Returns Returns true if the player has focus, false otherwise.","title":"hasFocus"},{"location":"engine/player/#moveby","text":"moveBy(dx, dy) Moves the player by a ( dx , dy ) offset after the physics update of the current framestep. This is similar to calling player.transform.translateBy(dx, dy) in lateUpdate() . See also: lateUpdate , translateBy . Available since: Open Surge 0.6.1 Arguments dx : number. Horizontal offset in pixels. dy : number. Vertical offset in pixels. Example // Let's compare player.moveBy() to // player.transform.translateBy() dx = 5 ; dy = 0 ; // this moves the player AFTER the physics update player . moveBy ( dx , dy ); // this moves the player BEFORE the physics update // (immediately), unless you call it in lateUpdate() player . transform . translateBy ( dx , dy );","title":"moveBy"},{"location":"engine/player/#move","text":"move(offset) Moves the player by the given offset after the physics update of the current framestep. Calling player.move(offset) is equivalent to calling player.moveBy(offset.x, offset.y) . See also: moveBy . Available since: Open Surge 0.6.1 Arguments offset : Vector2 object. Offset vector.","title":"move"},{"location":"engine/player/#transforminto","text":"player.transformInto(characterName) Transforms the player into the character named characterName . The transformation succeeds only if there is such a character. Available since: Open Surge 0.6.1 Arguments characterName : string. The name of a character, as defined in a .chr file. Returns Returns true if the transformation is successful. Transforming a player into itself is considered successful, but nothing happens in this case. // this player will become Surge player . transformInto ( \"Surge\" ); // this player will become Tux player . transformInto ( \"Tux\" ); // the following transformation will fail: if (! player . transformInto ( \"non-existent-character\" )) Console . print ( \"No transformation took place!\" ); // After a successful transformation: // - player.name will change; // - player.id will not change!","title":"transformInto"},{"location":"engine/prefs/","text":"Prefs Prefs is a SurgeEngine component used to save/load data to/from the disk (permanent storage). Prefs is a (key, value) storage that works like a Dictionary , but its data can be persisted between game sessions. Example using SurgeEngine.Prefs ; // Run the Application multiple times and see // how the counter increments object \"Application\" { state \"main\" { Prefs [ \"counter\" ] += 1 ; Console . print ( \"counter: \" + Prefs [ \"counter\" ]); state = \"idle\" ; } state \"idle\" { } fun constructor () { if (! Prefs . has ( \"counter\" )) Prefs [ \"counter\" ] = 0 ; } } Functions get get(key) Gets the value of the specified key. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments key : string. The key must always be a string. Returns Returns the value associated with the specified key, or null if there is no such value. set set(key, value) Sets the value of the specified key. Instead of calling set() directly, you may equivalently use the [ ] operator. Arguments key : string. The key must always be a string. value : any type. The value you want to store. clear clear() Removes all entries from Prefs. Use this very carefully, because data will be lost. delete delete(key) Deletes the entry having the specified key. Arguments key : string. The key of the entry to be removed. has has(key) Checks if a specific entry exists. Arguments key : string. The key of the entry. Returns Returns true if the specified entry exists, false otherwise. save save() Writes the data to secondary storage. The data isn't saved immediately after you set an entry, but it is saved on key moments. Since the data is persisted automatically, normally you don't need to call this.","title":"Prefs"},{"location":"engine/prefs/#prefs","text":"Prefs is a SurgeEngine component used to save/load data to/from the disk (permanent storage). Prefs is a (key, value) storage that works like a Dictionary , but its data can be persisted between game sessions. Example using SurgeEngine.Prefs ; // Run the Application multiple times and see // how the counter increments object \"Application\" { state \"main\" { Prefs [ \"counter\" ] += 1 ; Console . print ( \"counter: \" + Prefs [ \"counter\" ]); state = \"idle\" ; } state \"idle\" { } fun constructor () { if (! Prefs . has ( \"counter\" )) Prefs [ \"counter\" ] = 0 ; } }","title":"Prefs"},{"location":"engine/prefs/#functions","text":"","title":"Functions"},{"location":"engine/prefs/#get","text":"get(key) Gets the value of the specified key. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments key : string. The key must always be a string. Returns Returns the value associated with the specified key, or null if there is no such value.","title":"get"},{"location":"engine/prefs/#set","text":"set(key, value) Sets the value of the specified key. Instead of calling set() directly, you may equivalently use the [ ] operator. Arguments key : string. The key must always be a string. value : any type. The value you want to store.","title":"set"},{"location":"engine/prefs/#clear","text":"clear() Removes all entries from Prefs. Use this very carefully, because data will be lost.","title":"clear"},{"location":"engine/prefs/#delete","text":"delete(key) Deletes the entry having the specified key. Arguments key : string. The key of the entry to be removed.","title":"delete"},{"location":"engine/prefs/#has","text":"has(key) Checks if a specific entry exists. Arguments key : string. The key of the entry. Returns Returns true if the specified entry exists, false otherwise.","title":"has"},{"location":"engine/prefs/#save","text":"save() Writes the data to secondary storage. The data isn't saved immediately after you set an entry, but it is saved on key moments. Since the data is persisted automatically, normally you don't need to call this.","title":"save"},{"location":"engine/screen/","text":"Screen Screen settings. The screen represents the backbuffer, i.e., the texture in which things are drawn. Example // display the size of the screen using SurgeEngine.Video.Screen ; object \"Application\" { width = Screen . width ; height = Screen . height ; state \"main\" { Console . print ( width + \"x\" + height ); state = \"done\" ; } state \"done\" { } } Properties width width : number, read-only. The width of the screen, in pixels. height height : number, read-only. The height of the screen, in pixels.","title":"Screen"},{"location":"engine/screen/#screen","text":"Screen settings. The screen represents the backbuffer, i.e., the texture in which things are drawn. Example // display the size of the screen using SurgeEngine.Video.Screen ; object \"Application\" { width = Screen . width ; height = Screen . height ; state \"main\" { Console . print ( width + \"x\" + height ); state = \"done\" ; } state \"done\" { } }","title":"Screen"},{"location":"engine/screen/#properties","text":"","title":"Properties"},{"location":"engine/screen/#width","text":"width : number, read-only. The width of the screen, in pixels.","title":"width"},{"location":"engine/screen/#height","text":"height : number, read-only. The height of the screen, in pixels.","title":"height"},{"location":"engine/sensor/","text":"Sensor A Sensor is used to detect collisions with bricks. Due to performance optimizations, passable bricks (or bricks that are too far off camera) can't be sensed. Example using SurgeEngine.Actor ; using SurgeEngine.Collisions.Sensor ; object \"SensorToy\" is \"entity\" { actor = Actor ( \"SensorToy\" ); sensor = Sensor ( 0 , - 25 , 1 , 50 ); // a vertical sensor state \"main\" { if ( sensor . status != null ) Console . print ( \"Got a brick of type \" + sensor . status ); } fun constructor () { sensor . visible = true ; } } Factory Sensor Collisions.Sensor(x, y, width, height) Spawns a new Sensor with the specified dimensions and having its top-left corner located at position ( x , y ) relative to the parent object. A Sensor is either a vertical or a horizontal bar that is 1-pixel thin. Both width and height must be positive integers, and at least one of them must be equal to 1. Arguments x : number. The x-position of the top-left corner of the sensor, relative to the parent object. y : number. The y-position of the top-left corner of the sensor, relative to the parent object. width : number. The width of the sensor, in pixels. Must be a positive integer. height : number. The height of the sensor, in pixels. Must be a positive integer. Returns A Sensor with the specified parameters. Properties status status : string | null , read-only. The type of the brick colliding with the sensor (either \"solid\" or \"cloud\" ). If the sensor isn't colliding with a brick, or if it's disabled, its status will be null . visible visible : boolean. Should the sensor be rendered? Useful for debugging. Defaults to false . enabled enabled : boolean. Indicates whether the sensor is enabled or not. Defaults to true . layer layer : string. The layer of this sensor. This property assumes one of the following values: \"default\" , \"green\" or \"yellow\" . If it's set to \"default\" , then all non-passable bricks and brick-like objects are sensed. If it's set to \"green\" , then all non-passable bricks and brick-like objects are sensed, except the ones in the yellow layer. Conversely, if it's set to \"yellow\" , then all non-passable bricks and brick-like objects are sensed, except the ones in the green layer. Available since: Open Surge 0.6.1","title":"Sensor"},{"location":"engine/sensor/#sensor","text":"A Sensor is used to detect collisions with bricks. Due to performance optimizations, passable bricks (or bricks that are too far off camera) can't be sensed. Example using SurgeEngine.Actor ; using SurgeEngine.Collisions.Sensor ; object \"SensorToy\" is \"entity\" { actor = Actor ( \"SensorToy\" ); sensor = Sensor ( 0 , - 25 , 1 , 50 ); // a vertical sensor state \"main\" { if ( sensor . status != null ) Console . print ( \"Got a brick of type \" + sensor . status ); } fun constructor () { sensor . visible = true ; } }","title":"Sensor"},{"location":"engine/sensor/#factory","text":"","title":"Factory"},{"location":"engine/sensor/#sensor_1","text":"Collisions.Sensor(x, y, width, height) Spawns a new Sensor with the specified dimensions and having its top-left corner located at position ( x , y ) relative to the parent object. A Sensor is either a vertical or a horizontal bar that is 1-pixel thin. Both width and height must be positive integers, and at least one of them must be equal to 1. Arguments x : number. The x-position of the top-left corner of the sensor, relative to the parent object. y : number. The y-position of the top-left corner of the sensor, relative to the parent object. width : number. The width of the sensor, in pixels. Must be a positive integer. height : number. The height of the sensor, in pixels. Must be a positive integer. Returns A Sensor with the specified parameters.","title":"Sensor"},{"location":"engine/sensor/#properties","text":"","title":"Properties"},{"location":"engine/sensor/#status","text":"status : string | null , read-only. The type of the brick colliding with the sensor (either \"solid\" or \"cloud\" ). If the sensor isn't colliding with a brick, or if it's disabled, its status will be null .","title":"status"},{"location":"engine/sensor/#visible","text":"visible : boolean. Should the sensor be rendered? Useful for debugging. Defaults to false .","title":"visible"},{"location":"engine/sensor/#enabled","text":"enabled : boolean. Indicates whether the sensor is enabled or not. Defaults to true .","title":"enabled"},{"location":"engine/sensor/#layer","text":"layer : string. The layer of this sensor. This property assumes one of the following values: \"default\" , \"green\" or \"yellow\" . If it's set to \"default\" , then all non-passable bricks and brick-like objects are sensed. If it's set to \"green\" , then all non-passable bricks and brick-like objects are sensed, except the ones in the yellow layer. Conversely, if it's set to \"yellow\" , then all non-passable bricks and brick-like objects are sensed, except the ones in the green layer. Available since: Open Surge 0.6.1","title":"layer"},{"location":"engine/sound/","text":"Sound The Sound object lets you play samples, which are short sounds like: jump, brake, select, hit, etc. Sounds are loaded entirely in the memory; therefore, this object is meant to be used only with samples. If you need to play longer things like music, consider using Music instead. Example using SurgeEngine.Audio.Sound ; // will play a sound every 5 seconds object \"SoundTest\" { sound = Sound ( \"samples/jump.wav\" ); state \"main\" { sound . play (); state = \"wait\" ; } state \"wait\" { if ( timeout ( 5.0 )) state = \"main\" ; } } Factory Sound Audio.Sound(path) Creates a Sound object associated with a certain file. Arguments path : string. The path of the sound - usually a file in the samples/ folder. Returns A Sound object. Properties playing playing : boolean, read-only. Will be true if the sound is playing. volume volume : number. The volume of the sound, a value between 0.0 and 1.0, inclusive (zero means silence). Functions play play() Plays the sound. stop stop() Stops the sound.","title":"Sound"},{"location":"engine/sound/#sound","text":"The Sound object lets you play samples, which are short sounds like: jump, brake, select, hit, etc. Sounds are loaded entirely in the memory; therefore, this object is meant to be used only with samples. If you need to play longer things like music, consider using Music instead. Example using SurgeEngine.Audio.Sound ; // will play a sound every 5 seconds object \"SoundTest\" { sound = Sound ( \"samples/jump.wav\" ); state \"main\" { sound . play (); state = \"wait\" ; } state \"wait\" { if ( timeout ( 5.0 )) state = \"main\" ; } }","title":"Sound"},{"location":"engine/sound/#factory","text":"","title":"Factory"},{"location":"engine/sound/#sound_1","text":"Audio.Sound(path) Creates a Sound object associated with a certain file. Arguments path : string. The path of the sound - usually a file in the samples/ folder. Returns A Sound object.","title":"Sound"},{"location":"engine/sound/#properties","text":"","title":"Properties"},{"location":"engine/sound/#playing","text":"playing : boolean, read-only. Will be true if the sound is playing.","title":"playing"},{"location":"engine/sound/#volume","text":"volume : number. The volume of the sound, a value between 0.0 and 1.0, inclusive (zero means silence).","title":"volume"},{"location":"engine/sound/#functions","text":"","title":"Functions"},{"location":"engine/sound/#play","text":"play() Plays the sound.","title":"play"},{"location":"engine/sound/#stop","text":"stop() Stops the sound.","title":"stop"},{"location":"engine/surgeengine/","text":"SurgeEngine The SurgeEngine plugin is the interface between SurgeScript (scripting language) and Open Surge (game engine). Example using SurgeEngine ; // Open Surge version object \"Application\" { state \"main\" { Console . print ( SurgeEngine . version ); state = \"blank\" ; } state \"blank\" { } } Properties version version : string, read-only. Version of the Open Surge Engine. mobile mobile : boolean, read-only. Whether or not the engine has been launched in mobile mode. The user may be playing on a mobile device or on a Desktop computer with the mobile mode enabled. Available since: Open Surge 0.6.1","title":"SurgeEngine"},{"location":"engine/surgeengine/#surgeengine","text":"The SurgeEngine plugin is the interface between SurgeScript (scripting language) and Open Surge (game engine). Example using SurgeEngine ; // Open Surge version object \"Application\" { state \"main\" { Console . print ( SurgeEngine . version ); state = \"blank\" ; } state \"blank\" { } }","title":"SurgeEngine"},{"location":"engine/surgeengine/#properties","text":"","title":"Properties"},{"location":"engine/surgeengine/#version","text":"version : string, read-only. Version of the Open Surge Engine.","title":"version"},{"location":"engine/surgeengine/#mobile","text":"mobile : boolean, read-only. Whether or not the engine has been launched in mobile mode. The user may be playing on a mobile device or on a Desktop computer with the mobile mode enabled. Available since: Open Surge 0.6.1","title":"mobile"},{"location":"engine/text/","text":"Text The Text object allows you to display custom texts in the game. The parent object is required to be an entity . Factory Text UI.Text(font) Spawns a new Text object with the given font name. If null is provided as the font name, then a default font will be used. Arguments font : string. The name of a font (defined in the fonts/ folder). Returns A Text object. Example using SurgeEngine.UI.Text ; using SurgeEngine.Transform ; using SurgeEngine.Player ; // Place this on your level to display // the name of the player object \"PlayerName\" is \"entity\" , \"awake\" { text = Text ( \"GoodNeighbors\" ); transform = Transform (); state \"main\" { // position the text player = Player . active ; transform . position = player . transform . position ; transform . translateBy ( 0 , - 50 ); // configure the text text . align = \"center\" ; text . text = player . name ; } } Properties text text : string. The text to be displayed. font font : string, read-only. The name of the font in use. size size : Vector2 object, read-only. The size, in pixels, of the rendered text. Available since: Open Surge 0.5.1 align align : string. The alignment of the text. One of the following: \"left\" , \"center\" , \"right\" . visible visible : boolean. Is the Text object visible? maxLength maxLength : number. The maximum number of characters to be displayed, ignoring tags and spaces. Available since: Open Surge 0.5.1 maxWidth maxWidth : number. The maximum width of the text, in pixels. Setting this value will enable wordwrap. zindex zindex : number. The zindex of the Text object. Defaults to 0.5. offset offset : Vector2 object. An (x,y) offset relative to the parent object. Defaults to zero.","title":"Text"},{"location":"engine/text/#text","text":"The Text object allows you to display custom texts in the game. The parent object is required to be an entity .","title":"Text"},{"location":"engine/text/#factory","text":"","title":"Factory"},{"location":"engine/text/#text_1","text":"UI.Text(font) Spawns a new Text object with the given font name. If null is provided as the font name, then a default font will be used. Arguments font : string. The name of a font (defined in the fonts/ folder). Returns A Text object. Example using SurgeEngine.UI.Text ; using SurgeEngine.Transform ; using SurgeEngine.Player ; // Place this on your level to display // the name of the player object \"PlayerName\" is \"entity\" , \"awake\" { text = Text ( \"GoodNeighbors\" ); transform = Transform (); state \"main\" { // position the text player = Player . active ; transform . position = player . transform . position ; transform . translateBy ( 0 , - 50 ); // configure the text text . align = \"center\" ; text . text = player . name ; } }","title":"Text"},{"location":"engine/text/#properties","text":"","title":"Properties"},{"location":"engine/text/#text_2","text":"text : string. The text to be displayed.","title":"text"},{"location":"engine/text/#font","text":"font : string, read-only. The name of the font in use.","title":"font"},{"location":"engine/text/#size","text":"size : Vector2 object, read-only. The size, in pixels, of the rendered text. Available since: Open Surge 0.5.1","title":"size"},{"location":"engine/text/#align","text":"align : string. The alignment of the text. One of the following: \"left\" , \"center\" , \"right\" .","title":"align"},{"location":"engine/text/#visible","text":"visible : boolean. Is the Text object visible?","title":"visible"},{"location":"engine/text/#maxlength","text":"maxLength : number. The maximum number of characters to be displayed, ignoring tags and spaces. Available since: Open Surge 0.5.1","title":"maxLength"},{"location":"engine/text/#maxwidth","text":"maxWidth : number. The maximum width of the text, in pixels. Setting this value will enable wordwrap.","title":"maxWidth"},{"location":"engine/text/#zindex","text":"zindex : number. The zindex of the Text object. Defaults to 0.5.","title":"zindex"},{"location":"engine/text/#offset","text":"offset : Vector2 object. An (x,y) offset relative to the parent object. Defaults to zero.","title":"offset"},{"location":"engine/transform/","text":"Transform Transform encapsulates a 2D Transform. It comes with functions for translating, rotating and scaling things - and it's very useful for games! Whenever you spawn a Transform on your object, you gain power to command its position, rotation and scale. The Transform component can only be spawned on entities . If an entity with a Transform component has any children, the transform of the children will be affected by the transform of their parent. Example: if you move an object, its children will be moved by the same amount. Factory Transform Transform() Spawns a Transform on the object. The object is required to be an entity . Returns A Transform object. Example using SurgeEngine.Actor ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // prints the position of this entity Console . print ( transform . position ); } } Properties position position : Vector2 object. The position of the object in world coordinates. Only use this property if you need to read the position of the object or to set it to a fixed value. If you need to move the entity, use translateBy instead. Example using SurgeEngine.Actor ; using SurgeEngine.Player ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // this will show the distance between // this entity and the active player player = Player . active ; Console . print ( distanceTo ( player )); } fun distanceTo ( obj ) { return transform . position . distanceTo ( obj . transform . position ); } } angle angle : number. The angle, in degrees, specifying the rotation of the object. Unless you need to read or to set the angle of the object to a pre-determined value, consider using rotate instead. localPosition localPosition : Vector2 object. The position of the object relative to the parent object. Only use this property if you need to read the position of the object or to set it to a fixed value. If you need to move the entity, use translateBy instead. localAngle localAngle : number. The angle, in degrees, relative to the angle of the parent object. Unless you need to read or to set the angle of the object to a pre-determined value, consider using rotate instead. localScale localScale : Vector2 object. The local scale of the object. A value of 1.0 in both axes means the default size. A value of 2.0, twice the default size, and so on. lossyScale lossyScale : Vector2 object, read-only. An approximation of the world scale of the object. It's not very accurate (the parent transform may be rotated and scaled), but it's useful. Available since: Open Surge 0.5.1 right right : Vector2 object, read-only. The right vector of the transform in world space. Unlike Vector2.right , this property considers the rotation of the transform. Available since: Open Surge 0.5.1 up up : Vector2 object, read-only. The up vector of the transform in world space. Unlike Vector2.up , this property considers the rotation of the transform. Available since: Open Surge 0.5.1 Functions translateBy translateBy(dx, dy) Translates (moves) the object by ( dx , dy ). Available since: Open Surge 0.5.1. See the note below. Arguments dx : number. Specifies how much to move the object in the x-axis. dy : number. Specifies how much to move the object in the y-axis. Example using SurgeEngine.Actor ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // move the entity at a speed of // 50 pixels/second, to the right transform . translateBy ( 50 * Time . delta , 0 ); // the command below would move it // at a speed of 30 pixels per FRAME //transform.translateBy(30, 0); // don't do this // since the framerate may vary across // different systems, it's advisable // to multiply the value by Time.delta // to make the behavior consistent. } } Note: in versions prior to 0.5.1, this function was called move . translate translate(delta) Translates the object by a delta vector. Arguments delta : Vector2 object. rotate rotate(deg) Rotates the object by deg degrees. Arguments deg : number. An angle in degrees. Example using SurgeEngine.Actor ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // rotate the entity at a speed of // 45 degrees per second transform . rotate ( 45 * Time . delta ); } } scaleBy scaleBy(sx, sy) Scales the object by horizontal and vertical factors sx and sy , respectively. Available since: Open Surge 0.6.1. Arguments sx : number. Horizontal scale factor. Value 1.0 means no change. sy : number. Vertical scale factor. Value 1.0 means no change. scale scale(resize) Scales the object by a resize vector. Available since: Open Surge 0.6.1. Arguments resize : Vector2 object. Vector2(1,1) means no change. lookAt lookAt(position) Rotates the transform so that its right vector points at the given position. Use this function to make your object look at some point in world space. Available since: Open Surge 0.5.1. See the note below. Arguments position : Vector2 object. A point in world space. Example using SurgeEngine.Actor ; using SurgeEngine.Player ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { player = Player . active ; transform . lookAt ( player . transform . position ); } } Note: in versions prior to 0.5.1, this function accepted a Transform parameter.","title":"Transform"},{"location":"engine/transform/#transform","text":"Transform encapsulates a 2D Transform. It comes with functions for translating, rotating and scaling things - and it's very useful for games! Whenever you spawn a Transform on your object, you gain power to command its position, rotation and scale. The Transform component can only be spawned on entities . If an entity with a Transform component has any children, the transform of the children will be affected by the transform of their parent. Example: if you move an object, its children will be moved by the same amount.","title":"Transform"},{"location":"engine/transform/#factory","text":"","title":"Factory"},{"location":"engine/transform/#transform_1","text":"Transform() Spawns a Transform on the object. The object is required to be an entity . Returns A Transform object. Example using SurgeEngine.Actor ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // prints the position of this entity Console . print ( transform . position ); } }","title":"Transform"},{"location":"engine/transform/#properties","text":"","title":"Properties"},{"location":"engine/transform/#position","text":"position : Vector2 object. The position of the object in world coordinates. Only use this property if you need to read the position of the object or to set it to a fixed value. If you need to move the entity, use translateBy instead. Example using SurgeEngine.Actor ; using SurgeEngine.Player ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // this will show the distance between // this entity and the active player player = Player . active ; Console . print ( distanceTo ( player )); } fun distanceTo ( obj ) { return transform . position . distanceTo ( obj . transform . position ); } }","title":"position"},{"location":"engine/transform/#angle","text":"angle : number. The angle, in degrees, specifying the rotation of the object. Unless you need to read or to set the angle of the object to a pre-determined value, consider using rotate instead.","title":"angle"},{"location":"engine/transform/#localposition","text":"localPosition : Vector2 object. The position of the object relative to the parent object. Only use this property if you need to read the position of the object or to set it to a fixed value. If you need to move the entity, use translateBy instead.","title":"localPosition"},{"location":"engine/transform/#localangle","text":"localAngle : number. The angle, in degrees, relative to the angle of the parent object. Unless you need to read or to set the angle of the object to a pre-determined value, consider using rotate instead.","title":"localAngle"},{"location":"engine/transform/#localscale","text":"localScale : Vector2 object. The local scale of the object. A value of 1.0 in both axes means the default size. A value of 2.0, twice the default size, and so on.","title":"localScale"},{"location":"engine/transform/#lossyscale","text":"lossyScale : Vector2 object, read-only. An approximation of the world scale of the object. It's not very accurate (the parent transform may be rotated and scaled), but it's useful. Available since: Open Surge 0.5.1","title":"lossyScale"},{"location":"engine/transform/#right","text":"right : Vector2 object, read-only. The right vector of the transform in world space. Unlike Vector2.right , this property considers the rotation of the transform. Available since: Open Surge 0.5.1","title":"right"},{"location":"engine/transform/#up","text":"up : Vector2 object, read-only. The up vector of the transform in world space. Unlike Vector2.up , this property considers the rotation of the transform. Available since: Open Surge 0.5.1","title":"up"},{"location":"engine/transform/#functions","text":"","title":"Functions"},{"location":"engine/transform/#translateby","text":"translateBy(dx, dy) Translates (moves) the object by ( dx , dy ). Available since: Open Surge 0.5.1. See the note below. Arguments dx : number. Specifies how much to move the object in the x-axis. dy : number. Specifies how much to move the object in the y-axis. Example using SurgeEngine.Actor ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // move the entity at a speed of // 50 pixels/second, to the right transform . translateBy ( 50 * Time . delta , 0 ); // the command below would move it // at a speed of 30 pixels per FRAME //transform.translateBy(30, 0); // don't do this // since the framerate may vary across // different systems, it's advisable // to multiply the value by Time.delta // to make the behavior consistent. } } Note: in versions prior to 0.5.1, this function was called move .","title":"translateBy"},{"location":"engine/transform/#translate","text":"translate(delta) Translates the object by a delta vector. Arguments delta : Vector2 object.","title":"translate"},{"location":"engine/transform/#rotate","text":"rotate(deg) Rotates the object by deg degrees. Arguments deg : number. An angle in degrees. Example using SurgeEngine.Actor ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // rotate the entity at a speed of // 45 degrees per second transform . rotate ( 45 * Time . delta ); } }","title":"rotate"},{"location":"engine/transform/#scaleby","text":"scaleBy(sx, sy) Scales the object by horizontal and vertical factors sx and sy , respectively. Available since: Open Surge 0.6.1. Arguments sx : number. Horizontal scale factor. Value 1.0 means no change. sy : number. Vertical scale factor. Value 1.0 means no change.","title":"scaleBy"},{"location":"engine/transform/#scale","text":"scale(resize) Scales the object by a resize vector. Available since: Open Surge 0.6.1. Arguments resize : Vector2 object. Vector2(1,1) means no change.","title":"scale"},{"location":"engine/transform/#lookat","text":"lookAt(position) Rotates the transform so that its right vector points at the given position. Use this function to make your object look at some point in world space. Available since: Open Surge 0.5.1. See the note below. Arguments position : Vector2 object. A point in world space. Example using SurgeEngine.Actor ; using SurgeEngine.Player ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { player = Player . active ; transform . lookAt ( player . transform . position ); } } Note: in versions prior to 0.5.1, this function accepted a Transform parameter.","title":"lookAt"},{"location":"engine/vector2/","text":"Vector2 Vector2 is a vector in 2D space. A vector is a mathematical object that has direction and length, usually represented by an arrow. A Vector2 can also be represented by a pair of (x,y) coordinates. In SurgeScript, vectors are immutable. Once created, you can't change their coordinates directly. In order to bring about change (say, in the position of an entity ), you need to create a new vector. Vector2 objects have been designed in such a way that their functions make them chainable. You can compose different vector operations using english-based terms, as in the example below: Example using SurgeEngine.Player ; using SurgeEngine.Vector2 ; ... player = Player . active ; ... l = Vector2 ( 6 , 8 ). scaledBy ( 0.5 ). length ; // number five u = Vector2 . right . rotatedBy ( 45 ). scaledBy ( 2 ); // a vector v = player . transform . position . translatedBy ( 5 , 0 ); // a vector ... Note: In Open Surge, the x-axis grows to the right of the screen and the y-axis grows downwards, as in many other 2D games and software. Factory Vector2 Vector2(x, y) Spawns a 2D vector with the given coordinates. Arguments x : number. The x-coordinate of the vector. y : number. The y-coordinate of the vector. Returns A Vector2 object. Example using SurgeEngine.Vector2 ; using SurgeEngine.Player ; // This entity will lock the player on position (100, 100) object \"PlayerLocker\" is \"entity\" , \"awake\" { pos = Vector2 ( 100 , 100 ); state \"main\" { player = Player . active ; player . transform . position = pos ; } } Static properties Vector2.up Vector2.up The unit up vector, i.e., (0,-1). Vector2.right Vector2.right The unit right vector, i.e., (1,0). Vector2.down Vector2.down The unit down vector, i.e., (0,1). Vector2.left Vector2.left The unit left vector, i.e., (-1,0). Vector2.zero Vector2.zero The zero vector, i.e., (0,0). Vector2.one Vector2.one The (1,1) vector. Available since: Open Surge 0.6.1 Properties x x : number, read-only. The x-coordinate of the vector. y y : number, read-only. The y-coordinate of the vector. length length : number, read-only. The length of the vector. angle angle : number, read-only. The angle, in degrees, between the vector and the positive x-axis (as in polar coordinates). Functions plus plus(v) Returns a Vector2 corresponding to the addition between this and v . Arguments v : Vector2 object. Returns Returns a Vector2 object corresponding to the result of the operation. Example a = Vector2 ( 3 , 1 ); b = Vector2 ( 2 , 1 ); c = a . plus ( b ); // c = (5,2) minus minus(v) Returns a Vector2 corresponding to the subtraction between this and v . Arguments v : Vector2 object. Returns Returns a Vector2 object corresponding to the result of the operation. Example v = Vector2 ( 5 , 5 ); zero = v . minus ( v ); // zero = (0,0) dot dot(v) Returns the dot product between this and v . Arguments v : Vector2 object. Returns Returns a number: the dot product between this and v . normalized normalized() Returns a normalized copy of this : the new vector will have length one. Returns Returns a Vector2 object corresponding to the result of the operation. directionTo directionTo(v) Returns a unit vector pointing to v (from this ). Arguments v : Vector2 object. Returns Returns a Vector2 of length one corresponding to the result of the operation. distanceTo distanceTo(v) Considering this and v as points in space, this function returns the distance between them. Arguments v : Vector2 object. Returns Returns a number corresponding to the specified distance. Example using SurgeEngine.Transform ; using SurgeEngine.Player ; // This entity will show the distance between // itself and the active player object \"DistanceDebugger\" is \"entity\" , \"awake\" { transform = Transform (); state \"main\" { player = Player . active ; playerpos = player . transform . position ; distance = transform . position . distanceTo ( playerpos ); Console . print ( distance ); } } translatedBy translatedBy(dx,dy) Returns a copy of this translated by (dx,dy) . Arguments dx : number. The offset to be added to the x-coordinate. dy : number. The offset to be added to the y-coordinate. Returns Returns a Vector2 object corresponding to the result of the operation. Example using SurgeEngine.Vector2 ; ... v = Vector2 . one . translatedBy ( 4 , 5 ); // (5,6) rotatedBy rotatedBy(deg) Returns a copy of this rotated counterclockwise by deg degrees. Arguments deg : number. The amount of degrees used on the rotation. Returns Returns a Vector2 object corresponding to the result of the operation. Example using SurgeEngine.Vector2 ; ... // A unit vector with an angle of 45 degrees // (relative to the positive x-axis) v = Vector2 . right . rotatedBy ( 45 ); Note: in Open Surge, the y-axis grows downwards. As an example, Vector2.right (1,0) rotated counterclockwise by 90 degrees will be the same as Vector2.up (0,-1). In addition, to rotate a Vector2 by deg degrees clockwise you may rotate it by -deg degrees counterclockwise. scaledBy scaledBy(s) Returns a copy of this scaled by s . The length of the resulting vector will be the length of this multiplied by s . Arguments s : number. The multiplier. Returns Returns a Vector2 object corresponding to the result of the operation. Example using SurgeEngine.Vector2 ; ... one = Vector2 . one ; two = one . scaledBy ( 2 ); // (2,2) half = one . scaledBy ( 0.5 ); // (0.5,0.5) projectedOn projectedOn(v) Returns a copy of this projected on nonzero vector v . Arguments v : Vector2 object. Returns Returns a Vector2 object corresponding to the result of the operation. toString toString() Converts the vector to a string. Returns Returns a string containing the coordinates of this . Example using SurgeEngine.Vector2 ; ... Console . print ( Vector2 . one ); // using toString() implicitly","title":"Vector2"},{"location":"engine/vector2/#vector2","text":"Vector2 is a vector in 2D space. A vector is a mathematical object that has direction and length, usually represented by an arrow. A Vector2 can also be represented by a pair of (x,y) coordinates. In SurgeScript, vectors are immutable. Once created, you can't change their coordinates directly. In order to bring about change (say, in the position of an entity ), you need to create a new vector. Vector2 objects have been designed in such a way that their functions make them chainable. You can compose different vector operations using english-based terms, as in the example below: Example using SurgeEngine.Player ; using SurgeEngine.Vector2 ; ... player = Player . active ; ... l = Vector2 ( 6 , 8 ). scaledBy ( 0.5 ). length ; // number five u = Vector2 . right . rotatedBy ( 45 ). scaledBy ( 2 ); // a vector v = player . transform . position . translatedBy ( 5 , 0 ); // a vector ... Note: In Open Surge, the x-axis grows to the right of the screen and the y-axis grows downwards, as in many other 2D games and software.","title":"Vector2"},{"location":"engine/vector2/#factory","text":"","title":"Factory"},{"location":"engine/vector2/#vector2_1","text":"Vector2(x, y) Spawns a 2D vector with the given coordinates. Arguments x : number. The x-coordinate of the vector. y : number. The y-coordinate of the vector. Returns A Vector2 object. Example using SurgeEngine.Vector2 ; using SurgeEngine.Player ; // This entity will lock the player on position (100, 100) object \"PlayerLocker\" is \"entity\" , \"awake\" { pos = Vector2 ( 100 , 100 ); state \"main\" { player = Player . active ; player . transform . position = pos ; } }","title":"Vector2"},{"location":"engine/vector2/#static-properties","text":"","title":"Static properties"},{"location":"engine/vector2/#vector2up","text":"Vector2.up The unit up vector, i.e., (0,-1).","title":"Vector2.up"},{"location":"engine/vector2/#vector2right","text":"Vector2.right The unit right vector, i.e., (1,0).","title":"Vector2.right"},{"location":"engine/vector2/#vector2down","text":"Vector2.down The unit down vector, i.e., (0,1).","title":"Vector2.down"},{"location":"engine/vector2/#vector2left","text":"Vector2.left The unit left vector, i.e., (-1,0).","title":"Vector2.left"},{"location":"engine/vector2/#vector2zero","text":"Vector2.zero The zero vector, i.e., (0,0).","title":"Vector2.zero"},{"location":"engine/vector2/#vector2one","text":"Vector2.one The (1,1) vector. Available since: Open Surge 0.6.1","title":"Vector2.one"},{"location":"engine/vector2/#properties","text":"","title":"Properties"},{"location":"engine/vector2/#x","text":"x : number, read-only. The x-coordinate of the vector.","title":"x"},{"location":"engine/vector2/#y","text":"y : number, read-only. The y-coordinate of the vector.","title":"y"},{"location":"engine/vector2/#length","text":"length : number, read-only. The length of the vector.","title":"length"},{"location":"engine/vector2/#angle","text":"angle : number, read-only. The angle, in degrees, between the vector and the positive x-axis (as in polar coordinates).","title":"angle"},{"location":"engine/vector2/#functions","text":"","title":"Functions"},{"location":"engine/vector2/#plus","text":"plus(v) Returns a Vector2 corresponding to the addition between this and v . Arguments v : Vector2 object. Returns Returns a Vector2 object corresponding to the result of the operation. Example a = Vector2 ( 3 , 1 ); b = Vector2 ( 2 , 1 ); c = a . plus ( b ); // c = (5,2)","title":"plus"},{"location":"engine/vector2/#minus","text":"minus(v) Returns a Vector2 corresponding to the subtraction between this and v . Arguments v : Vector2 object. Returns Returns a Vector2 object corresponding to the result of the operation. Example v = Vector2 ( 5 , 5 ); zero = v . minus ( v ); // zero = (0,0)","title":"minus"},{"location":"engine/vector2/#dot","text":"dot(v) Returns the dot product between this and v . Arguments v : Vector2 object. Returns Returns a number: the dot product between this and v .","title":"dot"},{"location":"engine/vector2/#normalized","text":"normalized() Returns a normalized copy of this : the new vector will have length one. Returns Returns a Vector2 object corresponding to the result of the operation.","title":"normalized"},{"location":"engine/vector2/#directionto","text":"directionTo(v) Returns a unit vector pointing to v (from this ). Arguments v : Vector2 object. Returns Returns a Vector2 of length one corresponding to the result of the operation.","title":"directionTo"},{"location":"engine/vector2/#distanceto","text":"distanceTo(v) Considering this and v as points in space, this function returns the distance between them. Arguments v : Vector2 object. Returns Returns a number corresponding to the specified distance. Example using SurgeEngine.Transform ; using SurgeEngine.Player ; // This entity will show the distance between // itself and the active player object \"DistanceDebugger\" is \"entity\" , \"awake\" { transform = Transform (); state \"main\" { player = Player . active ; playerpos = player . transform . position ; distance = transform . position . distanceTo ( playerpos ); Console . print ( distance ); } }","title":"distanceTo"},{"location":"engine/vector2/#translatedby","text":"translatedBy(dx,dy) Returns a copy of this translated by (dx,dy) . Arguments dx : number. The offset to be added to the x-coordinate. dy : number. The offset to be added to the y-coordinate. Returns Returns a Vector2 object corresponding to the result of the operation. Example using SurgeEngine.Vector2 ; ... v = Vector2 . one . translatedBy ( 4 , 5 ); // (5,6)","title":"translatedBy"},{"location":"engine/vector2/#rotatedby","text":"rotatedBy(deg) Returns a copy of this rotated counterclockwise by deg degrees. Arguments deg : number. The amount of degrees used on the rotation. Returns Returns a Vector2 object corresponding to the result of the operation. Example using SurgeEngine.Vector2 ; ... // A unit vector with an angle of 45 degrees // (relative to the positive x-axis) v = Vector2 . right . rotatedBy ( 45 ); Note: in Open Surge, the y-axis grows downwards. As an example, Vector2.right (1,0) rotated counterclockwise by 90 degrees will be the same as Vector2.up (0,-1). In addition, to rotate a Vector2 by deg degrees clockwise you may rotate it by -deg degrees counterclockwise.","title":"rotatedBy"},{"location":"engine/vector2/#scaledby","text":"scaledBy(s) Returns a copy of this scaled by s . The length of the resulting vector will be the length of this multiplied by s . Arguments s : number. The multiplier. Returns Returns a Vector2 object corresponding to the result of the operation. Example using SurgeEngine.Vector2 ; ... one = Vector2 . one ; two = one . scaledBy ( 2 ); // (2,2) half = one . scaledBy ( 0.5 ); // (0.5,0.5)","title":"scaledBy"},{"location":"engine/vector2/#projectedon","text":"projectedOn(v) Returns a copy of this projected on nonzero vector v . Arguments v : Vector2 object. Returns Returns a Vector2 object corresponding to the result of the operation.","title":"projectedOn"},{"location":"engine/vector2/#tostring","text":"toString() Converts the vector to a string. Returns Returns a string containing the coordinates of this . Example using SurgeEngine.Vector2 ; ... Console . print ( Vector2 . one ); // using toString() implicitly","title":"toString"},{"location":"engine/video/","text":"Video Video settings. Example // display the current Video mode using SurgeEngine.Video ; object \"Application\" { state \"main\" { Console . print ( Video . mode ); state = \"done\" ; } state \"done\" { } } Properties fullscreen fullscreen : boolean. Whether or not the engine is running on fullscreen mode. Use this property to toggle between windowed and fullscreen modes. Available since: Open Surge 0.6.1 mode mode : string. The current video mode. The following are the valid values: \"default\" : the size of the screen is set to its default. \"fill\" : the size of the screen is set to the size of the window. \"best-fit\" : similar to \"fill\" , except that the aspect ratio of the default size of the screen is maintained. Available since: Open Surge 0.6.1","title":"Video"},{"location":"engine/video/#video","text":"Video settings. Example // display the current Video mode using SurgeEngine.Video ; object \"Application\" { state \"main\" { Console . print ( Video . mode ); state = \"done\" ; } state \"done\" { } }","title":"Video"},{"location":"engine/video/#properties","text":"","title":"Properties"},{"location":"engine/video/#fullscreen","text":"fullscreen : boolean. Whether or not the engine is running on fullscreen mode. Use this property to toggle between windowed and fullscreen modes. Available since: Open Surge 0.6.1","title":"fullscreen"},{"location":"engine/video/#mode","text":"mode : string. The current video mode. The following are the valid values: \"default\" : the size of the screen is set to its default. \"fill\" : the size of the screen is set to the size of the window. \"best-fit\" : similar to \"fill\" , except that the aspect ratio of the default size of the screen is maintained. Available since: Open Surge 0.6.1","title":"mode"},{"location":"engine/web/","text":"Web Web routines. Functions launchURL launchURL(url) Launches a URL using the default web browser. It's mandatory to specify a protocol. The following protocols are currently supported: http:// , https:// , mailto: Arguments url : string. The URL to be launched. Example using SurgeEngine.Web ; object \"Application\" { // Remember to change the state // after calling launchURL state \"main\" { Web . launchURL ( \"http://opensurge2d.org\" ); state = \"done\" ; } state \"done\" { } } encodeURIComponent encodeURIComponent(str) Encodes a component of a Universal Resource Identifier (URI). It escapes all characters of the input string, except: A\u2013Z a\u2013z 0\u20139 - _ . ! ~ * ' ( ) Arguments str : string. The string to be escaped. Returns Returns the input string escaped as above. Example using SurgeEngine.Web ; // ... user = \"Jane Doe\" ; url = \"https://my.website.name/?user=\" + Web . encodeURIComponent ( user ); Console . print ( url ); // output: // https://my.website.name/?user=Jane%20Doe Available since: Open Surge 0.6.1","title":"Web"},{"location":"engine/web/#web","text":"Web routines.","title":"Web"},{"location":"engine/web/#functions","text":"","title":"Functions"},{"location":"engine/web/#launchurl","text":"launchURL(url) Launches a URL using the default web browser. It's mandatory to specify a protocol. The following protocols are currently supported: http:// , https:// , mailto: Arguments url : string. The URL to be launched. Example using SurgeEngine.Web ; object \"Application\" { // Remember to change the state // after calling launchURL state \"main\" { Web . launchURL ( \"http://opensurge2d.org\" ); state = \"done\" ; } state \"done\" { } }","title":"launchURL"},{"location":"engine/web/#encodeuricomponent","text":"encodeURIComponent(str) Encodes a component of a Universal Resource Identifier (URI). It escapes all characters of the input string, except: A\u2013Z a\u2013z 0\u20139 - _ . ! ~ * ' ( ) Arguments str : string. The string to be escaped. Returns Returns the input string escaped as above. Example using SurgeEngine.Web ; // ... user = \"Jane Doe\" ; url = \"https://my.website.name/?user=\" + Web . encodeURIComponent ( user ); Console . print ( url ); // output: // https://my.website.name/?user=Jane%20Doe Available since: Open Surge 0.6.1","title":"encodeURIComponent"},{"location":"reference/application/","text":"Application Represents the Application. You do not need to instantiate it, as it is instantiated automatically. This object can be accessed by any other object, in any script, simply by typing Application . Properties args args : Arguments object, read-only. Use this property to read the command line arguments. Functions exit exit() Exits the Application. crash crash(message) Exits the Application with an error message. Arguments message : string. The message to be displayed to the user. destroy destroy() A synonym for Application.exit() .","title":"Application"},{"location":"reference/application/#application","text":"Represents the Application. You do not need to instantiate it, as it is instantiated automatically. This object can be accessed by any other object, in any script, simply by typing Application .","title":"Application"},{"location":"reference/application/#properties","text":"","title":"Properties"},{"location":"reference/application/#args","text":"args : Arguments object, read-only. Use this property to read the command line arguments.","title":"args"},{"location":"reference/application/#functions","text":"","title":"Functions"},{"location":"reference/application/#exit","text":"exit() Exits the Application.","title":"exit"},{"location":"reference/application/#crash","text":"crash(message) Exits the Application with an error message. Arguments message : string. The message to be displayed to the user.","title":"crash"},{"location":"reference/application/#destroy","text":"destroy() A synonym for Application.exit() .","title":"destroy"},{"location":"reference/arguments/","text":"Arguments If you've launched your application via the command-line, this Array-like object can be used to read command-line arguments. This is available at Application.args . The example below prints all the arguments to the screen: // Method 1 (foreach) foreach ( argument in Application . args ) Console . print ( argument ); // Method 2 (for loops) for ( i = 0 ; i < Application . args . length ; i ++) Console . print ( Application . args [ i ]); // Or, alternatively: Console . print ( Application . args ); Properties length length : number, read-only. The number of command-line arguments, including the executable. Functions get get(index) Gets the specified command-line argument. Instead of calling get() , one may use equivalently the [ ] operator. Arguments index : integer number between 0 and Application.args.length - 1 , inclusive. Returns A string with the specified command-line argument, or null if there is no such argument. Example // Suppose that you run surgescript via the command-line: // surgescript test_args.ss executable = Application . args [ 0 ]; // \"surgescript\" script_file = Application . args [ 1 ]; // \"test_args.ss\" option option(optionName) Gets the value of a certain command-line option. Arguments optionName : string. The option you want to read. Returns A string featuring the value of the desired command-line option, or null if such an option hasn't been provided by the user. Example // Suppose that you run surgescript via the command-line: // surgescript test_args.ss --my-option 12345 my_option = Application . args . option ( \"--my-option\" ); // Options -p and --port are equivalent // surgescript test_args.ss -p 80 // surgescript test_args.ss --port 80 port = Application . args . option ( \"--port\" ) || Application . args . option ( \"-p\" ); // Default values (useful if the option is not present) // surgescript test_args.ss // surgescript test_args.ss --name alice name = Application . args . option ( \"--name\" ) || \"anonymous\" ; hasOption hasOption(optionName) Checks if the specified option is present in the command-line. Arguments optionName : string. Returns Returns true if the specified option is present in the command-line; or false otherwise. iterator iterator() Spawns an iterator. Returns An iterator to iterate over the command-line arguments. toString toString() Converts the command-line arguments to a string. Returns A string featuring the command-line arguments.","title":"Arguments"},{"location":"reference/arguments/#arguments","text":"If you've launched your application via the command-line, this Array-like object can be used to read command-line arguments. This is available at Application.args . The example below prints all the arguments to the screen: // Method 1 (foreach) foreach ( argument in Application . args ) Console . print ( argument ); // Method 2 (for loops) for ( i = 0 ; i < Application . args . length ; i ++) Console . print ( Application . args [ i ]); // Or, alternatively: Console . print ( Application . args );","title":"Arguments"},{"location":"reference/arguments/#properties","text":"","title":"Properties"},{"location":"reference/arguments/#length","text":"length : number, read-only. The number of command-line arguments, including the executable.","title":"length"},{"location":"reference/arguments/#functions","text":"","title":"Functions"},{"location":"reference/arguments/#get","text":"get(index) Gets the specified command-line argument. Instead of calling get() , one may use equivalently the [ ] operator. Arguments index : integer number between 0 and Application.args.length - 1 , inclusive. Returns A string with the specified command-line argument, or null if there is no such argument. Example // Suppose that you run surgescript via the command-line: // surgescript test_args.ss executable = Application . args [ 0 ]; // \"surgescript\" script_file = Application . args [ 1 ]; // \"test_args.ss\"","title":"get"},{"location":"reference/arguments/#option","text":"option(optionName) Gets the value of a certain command-line option. Arguments optionName : string. The option you want to read. Returns A string featuring the value of the desired command-line option, or null if such an option hasn't been provided by the user. Example // Suppose that you run surgescript via the command-line: // surgescript test_args.ss --my-option 12345 my_option = Application . args . option ( \"--my-option\" ); // Options -p and --port are equivalent // surgescript test_args.ss -p 80 // surgescript test_args.ss --port 80 port = Application . args . option ( \"--port\" ) || Application . args . option ( \"-p\" ); // Default values (useful if the option is not present) // surgescript test_args.ss // surgescript test_args.ss --name alice name = Application . args . option ( \"--name\" ) || \"anonymous\" ;","title":"option"},{"location":"reference/arguments/#hasoption","text":"hasOption(optionName) Checks if the specified option is present in the command-line. Arguments optionName : string. Returns Returns true if the specified option is present in the command-line; or false otherwise.","title":"hasOption"},{"location":"reference/arguments/#iterator","text":"iterator() Spawns an iterator. Returns An iterator to iterate over the command-line arguments.","title":"iterator"},{"location":"reference/arguments/#tostring","text":"toString() Converts the command-line arguments to a string. Returns A string featuring the command-line arguments.","title":"toString"},{"location":"reference/array/","text":"Array An Array is a collection of values organized in sequencial fashion. To instantiate an Array, use the [ value_1, value_2, ..., value_n ] syntax rather than the spawn() function. Example: object \"Application\" { // The 'characters' array hold 3 strings characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; state \"main\" { // who are the characters? Console . print ( \"The characters are:\" ); Console . print ( characters [ 0 ]); Console . print ( characters [ 1 ]); Console . print ( characters [ 2 ]); // how many characters? Console . print ( \"Number of characters: \" + characters . length ); } } Output: The characters are: Surge Neon Charge Number of characters: 3 Caution! Whenever you define an array, you spawn a new object. You are advised to NOT define arrays within states, because the code within the states run continuously. New objects will be created at every frame, not just once. In the above example, the characters array is defined as an object-level variable . Properties length length : number, read-only. The number of elements in the Array. Functions get get(index) Gets the specified element of the Array. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments index : integer number between 0 and this.length - 1 , inclusive. Returns The Array element at position index (0-based). Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; ... surge = characters [ 0 ]; // first element (\"Surge\") neon = characters [ 1 ]; // second element (\"Neon\") charge = characters [ 2 ]; // third element (\"Charge\") set set(index, value) Sets to value the element of the Array at position index . Instead of calling set() directly, you may equivalently use the [ ] operator. Arguments index : integer number between 0 and this.length - 1 , inclusive. value : any type. The new value to be placed on the Array. Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; characters [ 0 ] = \"Gimacian\" ; Console . print ( characters [ 0 ]); // Gimacian push push(value) Adds a new element to the end of the Array. Arguments value : any type. The element to be added to the Array. Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; characters . push ( \"Gimacian\" ); Console . print ( characters ); // [ \"Surge\", \"Neon\", \"Charge\", \"Gimacian\" ] pop pop() Removes the last element of the Array and returns it. Returns The removed element. shift shift() Removes the first element of the Array and returns it. Returns The removed element. unshift unshift(value) Adds a new element to the beginning of the Array. Arguments value : any type. The element to be added to the Array. clear clear() Clears the array. It will no longer hold any elements and its length will be set to zero. Available since: SurgeScript 0.5.3 indexOf indexOf(value) Search the Array for element value and return its position. Arguments value : any type. The element to be searched for. Returns The position of the searched element - a number between 0 and this.length - 1 , inclusive. If the desired element is not found, this function returns -1 . Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; ... two = characters . indexOf ( \"Neon\" ); // 2 gimacian = characters . indexOf ( \"Gimacian\" ); // -1 if ( gimacian < 0 ) Console . print ( \"Not found\" ); sort sort(cmpFun) Sorts the Array. If no comparison functor is provided ( cmpFun is null ), the Array will be sorted in ascending order. Arguments cmpFun : object | null. This functor implements function call(a, b) that compares two array elements as described in the example below. Returns The sorted array. The returned array is the same array as you called sort() on; it's not a copy. Example // this example will print the elements // of the Array in ascending order object \"Application\" { arr = [ 3 , 9 , 4 , 8 , 5 , 6 , 7 , 1 , 2 , 0 ]; state \"main\" { // sort and print the Array arr . sort ( null ); Console . print ( arr ); Application . exit (); } } Output: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] // this example will print the elements // of the Array in descending order object \"Application\" { arr = [ 3 , 9 , 4 , 8 , 5 , 6 , 7 , 1 , 2 , 0 ]; cmp = spawn ( \"Sort.OrderByDesc\" ); state \"main\" { // sort and print the Array arr . sort ( cmp ); Console . print ( arr ); Application . exit (); } } object \"Sort.OrderByDesc\" { // This function compares two // elements of the Array: a and b. // // It should return a number: // < 0 if a must come BEFORE b // = 0 if a and b are equivalent // > 0 if a must come AFTER b fun call ( a , b ) { // sort in descending order return b - a ; } } Output: [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ] reverse reverse() Reverses the order of the elements in the Array. shuffle shuffle() Shuffles the elements of the Array, placing its elements at random spots. iterator iterator() Spawns an iterator. Returns An iterator to loop through the elements of the Array. toString toString() Converts the Array to a string. Returns A string.","title":"Array"},{"location":"reference/array/#array","text":"An Array is a collection of values organized in sequencial fashion. To instantiate an Array, use the [ value_1, value_2, ..., value_n ] syntax rather than the spawn() function. Example: object \"Application\" { // The 'characters' array hold 3 strings characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; state \"main\" { // who are the characters? Console . print ( \"The characters are:\" ); Console . print ( characters [ 0 ]); Console . print ( characters [ 1 ]); Console . print ( characters [ 2 ]); // how many characters? Console . print ( \"Number of characters: \" + characters . length ); } } Output: The characters are: Surge Neon Charge Number of characters: 3 Caution! Whenever you define an array, you spawn a new object. You are advised to NOT define arrays within states, because the code within the states run continuously. New objects will be created at every frame, not just once. In the above example, the characters array is defined as an object-level variable .","title":"Array"},{"location":"reference/array/#properties","text":"","title":"Properties"},{"location":"reference/array/#length","text":"length : number, read-only. The number of elements in the Array.","title":"length"},{"location":"reference/array/#functions","text":"","title":"Functions"},{"location":"reference/array/#get","text":"get(index) Gets the specified element of the Array. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments index : integer number between 0 and this.length - 1 , inclusive. Returns The Array element at position index (0-based). Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; ... surge = characters [ 0 ]; // first element (\"Surge\") neon = characters [ 1 ]; // second element (\"Neon\") charge = characters [ 2 ]; // third element (\"Charge\")","title":"get"},{"location":"reference/array/#set","text":"set(index, value) Sets to value the element of the Array at position index . Instead of calling set() directly, you may equivalently use the [ ] operator. Arguments index : integer number between 0 and this.length - 1 , inclusive. value : any type. The new value to be placed on the Array. Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; characters [ 0 ] = \"Gimacian\" ; Console . print ( characters [ 0 ]); // Gimacian","title":"set"},{"location":"reference/array/#push","text":"push(value) Adds a new element to the end of the Array. Arguments value : any type. The element to be added to the Array. Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; characters . push ( \"Gimacian\" ); Console . print ( characters ); // [ \"Surge\", \"Neon\", \"Charge\", \"Gimacian\" ]","title":"push"},{"location":"reference/array/#pop","text":"pop() Removes the last element of the Array and returns it. Returns The removed element.","title":"pop"},{"location":"reference/array/#shift","text":"shift() Removes the first element of the Array and returns it. Returns The removed element.","title":"shift"},{"location":"reference/array/#unshift","text":"unshift(value) Adds a new element to the beginning of the Array. Arguments value : any type. The element to be added to the Array.","title":"unshift"},{"location":"reference/array/#clear","text":"clear() Clears the array. It will no longer hold any elements and its length will be set to zero. Available since: SurgeScript 0.5.3","title":"clear"},{"location":"reference/array/#indexof","text":"indexOf(value) Search the Array for element value and return its position. Arguments value : any type. The element to be searched for. Returns The position of the searched element - a number between 0 and this.length - 1 , inclusive. If the desired element is not found, this function returns -1 . Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; ... two = characters . indexOf ( \"Neon\" ); // 2 gimacian = characters . indexOf ( \"Gimacian\" ); // -1 if ( gimacian < 0 ) Console . print ( \"Not found\" );","title":"indexOf"},{"location":"reference/array/#sort","text":"sort(cmpFun) Sorts the Array. If no comparison functor is provided ( cmpFun is null ), the Array will be sorted in ascending order. Arguments cmpFun : object | null. This functor implements function call(a, b) that compares two array elements as described in the example below. Returns The sorted array. The returned array is the same array as you called sort() on; it's not a copy. Example // this example will print the elements // of the Array in ascending order object \"Application\" { arr = [ 3 , 9 , 4 , 8 , 5 , 6 , 7 , 1 , 2 , 0 ]; state \"main\" { // sort and print the Array arr . sort ( null ); Console . print ( arr ); Application . exit (); } } Output: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] // this example will print the elements // of the Array in descending order object \"Application\" { arr = [ 3 , 9 , 4 , 8 , 5 , 6 , 7 , 1 , 2 , 0 ]; cmp = spawn ( \"Sort.OrderByDesc\" ); state \"main\" { // sort and print the Array arr . sort ( cmp ); Console . print ( arr ); Application . exit (); } } object \"Sort.OrderByDesc\" { // This function compares two // elements of the Array: a and b. // // It should return a number: // < 0 if a must come BEFORE b // = 0 if a and b are equivalent // > 0 if a must come AFTER b fun call ( a , b ) { // sort in descending order return b - a ; } } Output: [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ]","title":"sort"},{"location":"reference/array/#reverse","text":"reverse() Reverses the order of the elements in the Array.","title":"reverse"},{"location":"reference/array/#shuffle","text":"shuffle() Shuffles the elements of the Array, placing its elements at random spots.","title":"shuffle"},{"location":"reference/array/#iterator","text":"iterator() Spawns an iterator. Returns An iterator to loop through the elements of the Array.","title":"iterator"},{"location":"reference/array/#tostring","text":"toString() Converts the Array to a string. Returns A string.","title":"toString"},{"location":"reference/boolean/","text":"Boolean Routines for booleans. The Boolean object is not supposed to be used directly. The functions below are available for primitive values of the boolean type. Functions valueOf valueOf() The primitive value of the boolean, i.e., the boolean itself. Returns The boolean. toString toString() Convert boolean to string. Returns The boolean converted to a string. equals equals(b) Compares the boolean to another boolean b . Arguments b : boolean. The value to compare the boolean to. Returns Returns true if the booleans are equal.","title":"Boolean"},{"location":"reference/boolean/#boolean","text":"Routines for booleans. The Boolean object is not supposed to be used directly. The functions below are available for primitive values of the boolean type.","title":"Boolean"},{"location":"reference/boolean/#functions","text":"","title":"Functions"},{"location":"reference/boolean/#valueof","text":"valueOf() The primitive value of the boolean, i.e., the boolean itself. Returns The boolean.","title":"valueOf"},{"location":"reference/boolean/#tostring","text":"toString() Convert boolean to string. Returns The boolean converted to a string.","title":"toString"},{"location":"reference/boolean/#equals","text":"equals(b) Compares the boolean to another boolean b . Arguments b : boolean. The value to compare the boolean to. Returns Returns true if the booleans are equal.","title":"equals"},{"location":"reference/console/","text":"Console The Console is a mechanism that allows users to interact with your app via a text-based interface. You can print data to the user and read data from the user. Functions print print(line) Prints a line to the console. Arguments line : string. The message to be printed. Example // this will print \"Hello, there!\" and quit object \"Application\" { state \"main\" { Console . print ( \"Hello, there!\" ); Application . exit (); } } write write(str) Writes a string to the console, without a line break at the end. Arguments str : string. The string to be written. readline readline() Reads a line from the standard input. Returns Returns the string just read, without a line break at the end. Example // will ask the name of the user until a name is given object \"Application\" { state \"main\" { Console . print ( \"Hey pal, what's your name? \" ); name = Console . readline (); if ( name != \"\" ) { Console . print ( \"Nice to meet you, \" + name ); Application . exit (); } } }","title":"Console"},{"location":"reference/console/#console","text":"The Console is a mechanism that allows users to interact with your app via a text-based interface. You can print data to the user and read data from the user.","title":"Console"},{"location":"reference/console/#functions","text":"","title":"Functions"},{"location":"reference/console/#print","text":"print(line) Prints a line to the console. Arguments line : string. The message to be printed. Example // this will print \"Hello, there!\" and quit object \"Application\" { state \"main\" { Console . print ( \"Hello, there!\" ); Application . exit (); } }","title":"print"},{"location":"reference/console/#write","text":"write(str) Writes a string to the console, without a line break at the end. Arguments str : string. The string to be written.","title":"write"},{"location":"reference/console/#readline","text":"readline() Reads a line from the standard input. Returns Returns the string just read, without a line break at the end. Example // will ask the name of the user until a name is given object \"Application\" { state \"main\" { Console . print ( \"Hey pal, what's your name? \" ); name = Console . readline (); if ( name != \"\" ) { Console . print ( \"Nice to meet you, \" + name ); Application . exit (); } } }","title":"readline"},{"location":"reference/date/","text":"Date Date is used to retrieve current date and time. You can access this object simply by typing Date . Example: // What day is today? object \"Application\" { // show the day state \"main\" { today = Date . year + \"-\" + f ( Date . month ) + \"-\" + f ( Date . day ); Console . print ( \"Today is \" + today ); Application . exit (); } // add a leading zero fun f ( x ) { if ( x >= 10 ) return x ; else return \"0\" + x ; } } Available since: SurgeScript 0.5.2 Properties year year : number, read-only. The current year. month month : number, read-only. Month of the year (1-12). day day : number. Day of the month (1-31). hour hour : number. Hours since midnight (0-23). minute minute : number. Minutes after the hour (0-59). second second : number. Seconds after the minute (0-59). weekday weekday : number. Days since Sunday (0-6). unixtime unixtime : number. Number of seconds since Jan 1st, 1970 00:00:00 UTC. Functions timezoneOffset timezoneOffset() The difference, in minutes, from the Coordinated Universal Time (UTC) to the timezone of the host. Example: if your timezone is UTC-03:00, this function returns -180. Available since: SurgeScript 0.5.2 Returns The timezone difference in minutes. toString toString() Converts the current date and time to a string. The string is formatted according to the ISO 8601 standard. Available since: SurgeScript 0.5.2 Returns The current date and time expressed according to ISO 8601.","title":"Date"},{"location":"reference/date/#date","text":"Date is used to retrieve current date and time. You can access this object simply by typing Date . Example: // What day is today? object \"Application\" { // show the day state \"main\" { today = Date . year + \"-\" + f ( Date . month ) + \"-\" + f ( Date . day ); Console . print ( \"Today is \" + today ); Application . exit (); } // add a leading zero fun f ( x ) { if ( x >= 10 ) return x ; else return \"0\" + x ; } } Available since: SurgeScript 0.5.2","title":"Date"},{"location":"reference/date/#properties","text":"","title":"Properties"},{"location":"reference/date/#year","text":"year : number, read-only. The current year.","title":"year"},{"location":"reference/date/#month","text":"month : number, read-only. Month of the year (1-12).","title":"month"},{"location":"reference/date/#day","text":"day : number. Day of the month (1-31).","title":"day"},{"location":"reference/date/#hour","text":"hour : number. Hours since midnight (0-23).","title":"hour"},{"location":"reference/date/#minute","text":"minute : number. Minutes after the hour (0-59).","title":"minute"},{"location":"reference/date/#second","text":"second : number. Seconds after the minute (0-59).","title":"second"},{"location":"reference/date/#weekday","text":"weekday : number. Days since Sunday (0-6).","title":"weekday"},{"location":"reference/date/#unixtime","text":"unixtime : number. Number of seconds since Jan 1st, 1970 00:00:00 UTC.","title":"unixtime"},{"location":"reference/date/#functions","text":"","title":"Functions"},{"location":"reference/date/#timezoneoffset","text":"timezoneOffset() The difference, in minutes, from the Coordinated Universal Time (UTC) to the timezone of the host. Example: if your timezone is UTC-03:00, this function returns -180. Available since: SurgeScript 0.5.2 Returns The timezone difference in minutes.","title":"timezoneOffset"},{"location":"reference/date/#tostring","text":"toString() Converts the current date and time to a string. The string is formatted according to the ISO 8601 standard. Available since: SurgeScript 0.5.2 Returns The current date and time expressed according to ISO 8601.","title":"toString"},{"location":"reference/dictionary/","text":"Dictionary A Dictionary is a collection of key-value pairs. Dictionary keys are strings. Their corresponding values can be of any type. To create a Dictionary, use the { key_1: value_1, key_2: value_2, ..., key_n: value_n } syntax rather than the spawn() function. Example: object \"Application\" { dictionary = { \"Surge\" : 35 , \"Neon\" : 20 , \"Charge\" : 37.5 , \"Gimacian\" : 70 }; state \"main\" { // usage example Console . print ( dictionary [ \"Surge\" ]); // will print 35 Console . print ( dictionary [ \"Neon\" ]); // will print 20 // will print all entries foreach ( entry in dictionary ) Console . print ( entry . key + \": \" + entry . value ); // done! Application . exit (); } } Output: 35 20 Surge: 35 Neon: 20 Charge: 37.5 Gimacian: 70 Caution! Whenever you define a dictionary, you spawn a new object. You are advised to NOT define dictionaries within states, because the code within the states run continuously. New objects will be created at every frame, not just once. In the above example, dictionary is defined as an object-level variable . Properties count count : number, read-only. The number of elements in the Dictionary. Functions get get(key) Gets the value of the specified key in the Dictionary. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments key : string. Returns The value corresponding to the specified key, or null if there is no such an entry in the Dictionary. Example dict = { \"Surge\" : 10 }; ten = dict [ \"Surge\" ]; set set(key, value) Sets the value of the specified key in the Dictionary. Instead of calling set() directly, you may equivalently use the [ ] operator. Arguments key : string. value : any type. Example dict = { }; dict [ \"Surge\" ] = 10 ; clear clear() Removes all entries from the Dictionary. delete delete(key) Deletes the entry having the specified key. Arguments key : string. The key of the entry to be removed. has has(key) Checks if an entry having the specified key belongs to the Dictionary. Arguments key : string. The key of the entry. Returns Returns true if the Dictionary has such an entry. keys keys() Gets a collection containing the keys of the Dictionary. Returns Returns a new Array containing the keys of the Dictionary. iterator iterator() Spawns an iterator. Returns An iterator to loop through the elements of the Dictionary. toString toString() Converts the Dictionary to a string. Returns A string.","title":"Dictionary"},{"location":"reference/dictionary/#dictionary","text":"A Dictionary is a collection of key-value pairs. Dictionary keys are strings. Their corresponding values can be of any type. To create a Dictionary, use the { key_1: value_1, key_2: value_2, ..., key_n: value_n } syntax rather than the spawn() function. Example: object \"Application\" { dictionary = { \"Surge\" : 35 , \"Neon\" : 20 , \"Charge\" : 37.5 , \"Gimacian\" : 70 }; state \"main\" { // usage example Console . print ( dictionary [ \"Surge\" ]); // will print 35 Console . print ( dictionary [ \"Neon\" ]); // will print 20 // will print all entries foreach ( entry in dictionary ) Console . print ( entry . key + \": \" + entry . value ); // done! Application . exit (); } } Output: 35 20 Surge: 35 Neon: 20 Charge: 37.5 Gimacian: 70 Caution! Whenever you define a dictionary, you spawn a new object. You are advised to NOT define dictionaries within states, because the code within the states run continuously. New objects will be created at every frame, not just once. In the above example, dictionary is defined as an object-level variable .","title":"Dictionary"},{"location":"reference/dictionary/#properties","text":"","title":"Properties"},{"location":"reference/dictionary/#count","text":"count : number, read-only. The number of elements in the Dictionary.","title":"count"},{"location":"reference/dictionary/#functions","text":"","title":"Functions"},{"location":"reference/dictionary/#get","text":"get(key) Gets the value of the specified key in the Dictionary. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments key : string. Returns The value corresponding to the specified key, or null if there is no such an entry in the Dictionary. Example dict = { \"Surge\" : 10 }; ten = dict [ \"Surge\" ];","title":"get"},{"location":"reference/dictionary/#set","text":"set(key, value) Sets the value of the specified key in the Dictionary. Instead of calling set() directly, you may equivalently use the [ ] operator. Arguments key : string. value : any type. Example dict = { }; dict [ \"Surge\" ] = 10 ;","title":"set"},{"location":"reference/dictionary/#clear","text":"clear() Removes all entries from the Dictionary.","title":"clear"},{"location":"reference/dictionary/#delete","text":"delete(key) Deletes the entry having the specified key. Arguments key : string. The key of the entry to be removed.","title":"delete"},{"location":"reference/dictionary/#has","text":"has(key) Checks if an entry having the specified key belongs to the Dictionary. Arguments key : string. The key of the entry. Returns Returns true if the Dictionary has such an entry.","title":"has"},{"location":"reference/dictionary/#keys","text":"keys() Gets a collection containing the keys of the Dictionary. Returns Returns a new Array containing the keys of the Dictionary.","title":"keys"},{"location":"reference/dictionary/#iterator","text":"iterator() Spawns an iterator. Returns An iterator to loop through the elements of the Dictionary.","title":"iterator"},{"location":"reference/dictionary/#tostring","text":"toString() Converts the Dictionary to a string. Returns A string.","title":"toString"},{"location":"reference/gc/","text":"GC SurgeScript features a Garbage Collector (GC) that automatically disposes objects that cannot be reached from the root (i.e., their references are lost). The Garbage Collector is available at System.gc . Generally, you do not need to modify any of its settings. Properties interval interval : number, read-only. Every interval seconds, the garbage collector will be called automatically. Note: this property is read-only since SurgeScript 0.6.0. objectCount objectCount : number, read-only. How many objects were disposed when the garbage collector was last called. Functions collect collect() Calls the Garbage Collector manually. You generally don't need to call this.","title":"GC"},{"location":"reference/gc/#gc","text":"SurgeScript features a Garbage Collector (GC) that automatically disposes objects that cannot be reached from the root (i.e., their references are lost). The Garbage Collector is available at System.gc . Generally, you do not need to modify any of its settings.","title":"GC"},{"location":"reference/gc/#properties","text":"","title":"Properties"},{"location":"reference/gc/#interval","text":"interval : number, read-only. Every interval seconds, the garbage collector will be called automatically. Note: this property is read-only since SurgeScript 0.6.0.","title":"interval"},{"location":"reference/gc/#objectcount","text":"objectCount : number, read-only. How many objects were disposed when the garbage collector was last called.","title":"objectCount"},{"location":"reference/gc/#functions","text":"","title":"Functions"},{"location":"reference/gc/#collect","text":"collect() Calls the Garbage Collector manually. You generally don't need to call this.","title":"collect"},{"location":"reference/iterator/","text":"Iterator In SurgeScript, Iterator is an abstract contract, or protocol, that define a set of functions that should be written in concrete implementations. If you're familiar with object oriented programming, Iterator is an interface. Iterators are used to traverse containers / collections / data structures and access its elements. Concrete implementations of Iterator include: ArrayIterator and DictionaryIterator . If you wish to write your own iterators , you need to specify the functions described below . The data structure that you wish to traverse should include an iterator() function that spawns the concrete implementation of the Iterator. Thus, the parent object of the Iterator will be the structure to be traversed. The basic usage of an Iterator is as follows: // container is an object such as an Array iterator = container . iterator (); // spawn an iterator to traverse the container while ( iterator . hasNext ()) { element = iterator . next (); Console . print ( element ); } Functions hasNext hasNext() Checks if there are more elements to be accessed in the iteration. Returns Returns true if there are more elements to be visited, or false otherwise. next next() Gets the next element of the container and advances the iteration. Returns The next element of the container, or null if there is no such element. The first call to next() returns the first element of the container, and so on.","title":"Iterator"},{"location":"reference/iterator/#iterator","text":"In SurgeScript, Iterator is an abstract contract, or protocol, that define a set of functions that should be written in concrete implementations. If you're familiar with object oriented programming, Iterator is an interface. Iterators are used to traverse containers / collections / data structures and access its elements. Concrete implementations of Iterator include: ArrayIterator and DictionaryIterator . If you wish to write your own iterators , you need to specify the functions described below . The data structure that you wish to traverse should include an iterator() function that spawns the concrete implementation of the Iterator. Thus, the parent object of the Iterator will be the structure to be traversed. The basic usage of an Iterator is as follows: // container is an object such as an Array iterator = container . iterator (); // spawn an iterator to traverse the container while ( iterator . hasNext ()) { element = iterator . next (); Console . print ( element ); }","title":"Iterator"},{"location":"reference/iterator/#functions","text":"","title":"Functions"},{"location":"reference/iterator/#hasnext","text":"hasNext() Checks if there are more elements to be accessed in the iteration. Returns Returns true if there are more elements to be visited, or false otherwise.","title":"hasNext"},{"location":"reference/iterator/#next","text":"next() Gets the next element of the container and advances the iteration. Returns The next element of the container, or null if there is no such element. The first call to next() returns the first element of the container, and so on.","title":"next"},{"location":"reference/math/","text":"Math Built-in mathematical functions. The Math object can be accessed simply by typing Math . Examples: // Math functions two = Math . sqrt ( 4 ); // square root of 4 eight = Math . pow ( 2 , 3 ); // 2 raised to the 3rd power zero = Math . sin ( 0 ); // sine of 0 seven = Math . max ( 5 , 7 ); // maximum of 5 and 7 Properties pi pi : number, read-only. An approximation of pi (3.1415926535...) epsilon epsilon : number, read-only. The difference between 1 and the smallest floating point number that is greater than 1. infinity infinity : number, read-only. A floating point representation of positive infinity. NaN NaN : number, read-only. A numeric data type representing Not-a-Number. Available since: SurgeScript 0.5.3 Functions sqrt sqrt(x) Square root function. Arguments x : number. Returns The square root of x . pow pow(x, p) Raise to power. Arguments x : number. The base. p : number. The exponent. Returns Returns x raised to the p power. exp e(x) Exponential function. Arguments x : number. Returns Returns e raised to the x power. log log(x) Natural logarithm. Arguments x : number. Returns The natural logarithm (base e ) of x . log10 log10(x) Base 10 logarithm. Arguments x : number. Returns The base 10 logarithm of x . sin sin(x) Sine function. Arguments x : number. Angle in radians. Returns The sine of x . cos cos(x) Cosine function. Arguments x : number. Angle in radians. Returns The cosine of x . tan tan(x) Tangent function. Arguments x : number. Angle in radians. Returns The tangent of x . asin asin(x) Arc-sine function. Arguments x : number. Returns The angle in radians whose sine is x . acos acos(x) Arc-cosine function. Arguments x : number. Returns The angle in radians whose cosine is x . atan atan(x) Arc-tangent function. Arguments x : number. Returns The angle in radians whose tangent is x . atan2 atan2(y, x) Function atan2. Arguments y : number. x : number. Returns The angle, in radians, between the positive x-axis and the (x, y) vector. deg2rad deg2rad(degrees) Converts degrees to radians. Available since: SurgeScript 0.5.3 Arguments degrees : number. Returns The converted value. rad2deg rad2deg(radians) Converts radians to degrees. Available since: SurgeScript 0.5.3 Arguments radians : number. Returns The converted value. random random() Random value. Returns A random number between 0 (inclusive) and 1 (exclusive). floor floor(x) Floor function. Arguments x : number. Returns The largest integer less or equal than x . ceil ceil(x) Ceiling function. Arguments x : number. Returns The smallest integer greater or equal than x . round round(x) Round to the nearest integer. Arguments x : number. Returns Returns x rounded to the nearest integer. If the fraction of x is 0.5, this function uses the commercial rounding tie-breaking method. trunc trunc(x) Truncate to integer. Available since: SurgeScript 0.6.0 Arguments x : number. Returns The nearest integer not greater in magnitude than x . mod mod(x, y) Modulo operation. This is used to get the value x mod y - the modulo - defined as the remainder of the division of x by y that has the sign of the divisor y . Info The modulo x mod y may differ from the remainder x % y . The former has the sign of the divisor y , whereas the latter has the sign of the dividend x . When x and y have the same sign, the modulo and the remainder are equal. When the signs differ, modulo and remainder differ by y . Arguments x : number. The dividend. y : number. The divisor. Returns The modulo x mod y . Note The modulo x mod y is returned since SurgeScript 0.6.0. The remainder x % y was returned on SurgeScript 0.5.x. Example x = 5 ; y = 3 ; Console . print ( Math . mod ( x , y )); // 2 Console . print ( x % y ); // 2 Console . print ( Math . mod (- x , - y )); // -2 Console . print (- x % - y ); // -2 Console . print ( Math . mod (- x , y )); // 1 Console . print (- x % y ); // -2 Console . print ( Math . mod ( x , - y )); // -1 Console . print ( x % - y ); // 2 sign sign(x) The sign of x : 1 if x is non-negative, -1 otherwise. Arguments x : number. Returns Returns 1 if x is positive or zero; or -1 if x is negative. signum signum(x) Function signum( x ) returns 1 if x is positive, 0 if is x is zero, or -1 if x is negative. Available since: SurgeScript 0.5.4 Arguments x : number. Returns Returns 1 if x is positive, 0 if is x is zero, or -1 if x is negative. abs abs(x) Absolute value of x . Arguments x : number. Returns Returns -x if x is negative, or x otherwise. min min(x, y) The minimum of two values. Arguments x : number. y : number. Returns Returns the minimum of x and y . max max(x, y) The maximum of two values. Arguments x : number. y : number. Returns Returns the maximum of x and y . clamp clamp(val, min, max) Clamps a value between a minimum and a maximum. Arguments val : number. The value to be clamped. min : number. Minimum value. max : number. Maximum value. Returns Returns val clamped between min and max . Function clamp behave as follows: if val < min , it returns min if val > max , it returns max otherwise, it returns val approximately approximately(x, y) Compares two floating point values. Since comparing two floating point numbers for equality directly may result in inaccuracies, this is a handy function. Arguments x : number. y : number. Returns Returns true if x and y are \"approximately\" equal. lerp lerp(a, b, t) Linear interpolation. Arguments a : number. b : number. t : number. A value between 0 and 1. Returns Returns the linear interpolation between a and b by t . Value t is clamped automatically to the [0, 1] range. As an example, note that lerp : returns a if t is 0 returns b if t is 1 returns (a + b) / 2 if t is 0.5 smoothstep smoothstep(a, b, t) Interpolation smoothing at the limits. Arguments a : number. b : number. t : number. A value between 0 and 1. Returns Returns an interpolated value between a and b by t . Unlike lerp , smoothstep is smooth at the limits. This is useful to create smooth transitions and animations. Value t is clamped automatically to the [0, 1] range. lerpAngle lerpAngle(alpha, beta, t) Linear interpolation of angles alpha and beta given in degrees. Unlike lerp , lerpAngle can interpolate angles when they wrap around 360 degrees. Available since: SurgeScript 0.5.4.1 Arguments alpha : number. A value in degrees. beta : number. A value in degrees. t : number. A value between 0 and 1. Returns Returns the linear interpolation between angles alpha and beta , given in degrees, by t . deltaAngle deltaAngle(alpha, beta) The shortest difference between angles alpha and beta given in degrees. Available since: SurgeScript 0.5.4.1 Arguments alpha : number. A value in degrees. beta : number. A value in degrees. Returns Returns, in degrees, the shortest difference between the angles.","title":"Math"},{"location":"reference/math/#math","text":"Built-in mathematical functions. The Math object can be accessed simply by typing Math . Examples: // Math functions two = Math . sqrt ( 4 ); // square root of 4 eight = Math . pow ( 2 , 3 ); // 2 raised to the 3rd power zero = Math . sin ( 0 ); // sine of 0 seven = Math . max ( 5 , 7 ); // maximum of 5 and 7","title":"Math"},{"location":"reference/math/#properties","text":"","title":"Properties"},{"location":"reference/math/#pi","text":"pi : number, read-only. An approximation of pi (3.1415926535...)","title":"pi"},{"location":"reference/math/#epsilon","text":"epsilon : number, read-only. The difference between 1 and the smallest floating point number that is greater than 1.","title":"epsilon"},{"location":"reference/math/#infinity","text":"infinity : number, read-only. A floating point representation of positive infinity.","title":"infinity"},{"location":"reference/math/#nan","text":"NaN : number, read-only. A numeric data type representing Not-a-Number. Available since: SurgeScript 0.5.3","title":"NaN"},{"location":"reference/math/#functions","text":"","title":"Functions"},{"location":"reference/math/#sqrt","text":"sqrt(x) Square root function. Arguments x : number. Returns The square root of x .","title":"sqrt"},{"location":"reference/math/#pow","text":"pow(x, p) Raise to power. Arguments x : number. The base. p : number. The exponent. Returns Returns x raised to the p power.","title":"pow"},{"location":"reference/math/#exp","text":"e(x) Exponential function. Arguments x : number. Returns Returns e raised to the x power.","title":"exp"},{"location":"reference/math/#log","text":"log(x) Natural logarithm. Arguments x : number. Returns The natural logarithm (base e ) of x .","title":"log"},{"location":"reference/math/#log10","text":"log10(x) Base 10 logarithm. Arguments x : number. Returns The base 10 logarithm of x .","title":"log10"},{"location":"reference/math/#sin","text":"sin(x) Sine function. Arguments x : number. Angle in radians. Returns The sine of x .","title":"sin"},{"location":"reference/math/#cos","text":"cos(x) Cosine function. Arguments x : number. Angle in radians. Returns The cosine of x .","title":"cos"},{"location":"reference/math/#tan","text":"tan(x) Tangent function. Arguments x : number. Angle in radians. Returns The tangent of x .","title":"tan"},{"location":"reference/math/#asin","text":"asin(x) Arc-sine function. Arguments x : number. Returns The angle in radians whose sine is x .","title":"asin"},{"location":"reference/math/#acos","text":"acos(x) Arc-cosine function. Arguments x : number. Returns The angle in radians whose cosine is x .","title":"acos"},{"location":"reference/math/#atan","text":"atan(x) Arc-tangent function. Arguments x : number. Returns The angle in radians whose tangent is x .","title":"atan"},{"location":"reference/math/#atan2","text":"atan2(y, x) Function atan2. Arguments y : number. x : number. Returns The angle, in radians, between the positive x-axis and the (x, y) vector.","title":"atan2"},{"location":"reference/math/#deg2rad","text":"deg2rad(degrees) Converts degrees to radians. Available since: SurgeScript 0.5.3 Arguments degrees : number. Returns The converted value.","title":"deg2rad"},{"location":"reference/math/#rad2deg","text":"rad2deg(radians) Converts radians to degrees. Available since: SurgeScript 0.5.3 Arguments radians : number. Returns The converted value.","title":"rad2deg"},{"location":"reference/math/#random","text":"random() Random value. Returns A random number between 0 (inclusive) and 1 (exclusive).","title":"random"},{"location":"reference/math/#floor","text":"floor(x) Floor function. Arguments x : number. Returns The largest integer less or equal than x .","title":"floor"},{"location":"reference/math/#ceil","text":"ceil(x) Ceiling function. Arguments x : number. Returns The smallest integer greater or equal than x .","title":"ceil"},{"location":"reference/math/#round","text":"round(x) Round to the nearest integer. Arguments x : number. Returns Returns x rounded to the nearest integer. If the fraction of x is 0.5, this function uses the commercial rounding tie-breaking method.","title":"round"},{"location":"reference/math/#trunc","text":"trunc(x) Truncate to integer. Available since: SurgeScript 0.6.0 Arguments x : number. Returns The nearest integer not greater in magnitude than x .","title":"trunc"},{"location":"reference/math/#mod","text":"mod(x, y) Modulo operation. This is used to get the value x mod y - the modulo - defined as the remainder of the division of x by y that has the sign of the divisor y . Info The modulo x mod y may differ from the remainder x % y . The former has the sign of the divisor y , whereas the latter has the sign of the dividend x . When x and y have the same sign, the modulo and the remainder are equal. When the signs differ, modulo and remainder differ by y . Arguments x : number. The dividend. y : number. The divisor. Returns The modulo x mod y . Note The modulo x mod y is returned since SurgeScript 0.6.0. The remainder x % y was returned on SurgeScript 0.5.x. Example x = 5 ; y = 3 ; Console . print ( Math . mod ( x , y )); // 2 Console . print ( x % y ); // 2 Console . print ( Math . mod (- x , - y )); // -2 Console . print (- x % - y ); // -2 Console . print ( Math . mod (- x , y )); // 1 Console . print (- x % y ); // -2 Console . print ( Math . mod ( x , - y )); // -1 Console . print ( x % - y ); // 2","title":"mod"},{"location":"reference/math/#sign","text":"sign(x) The sign of x : 1 if x is non-negative, -1 otherwise. Arguments x : number. Returns Returns 1 if x is positive or zero; or -1 if x is negative.","title":"sign"},{"location":"reference/math/#signum","text":"signum(x) Function signum( x ) returns 1 if x is positive, 0 if is x is zero, or -1 if x is negative. Available since: SurgeScript 0.5.4 Arguments x : number. Returns Returns 1 if x is positive, 0 if is x is zero, or -1 if x is negative.","title":"signum"},{"location":"reference/math/#abs","text":"abs(x) Absolute value of x . Arguments x : number. Returns Returns -x if x is negative, or x otherwise.","title":"abs"},{"location":"reference/math/#min","text":"min(x, y) The minimum of two values. Arguments x : number. y : number. Returns Returns the minimum of x and y .","title":"min"},{"location":"reference/math/#max","text":"max(x, y) The maximum of two values. Arguments x : number. y : number. Returns Returns the maximum of x and y .","title":"max"},{"location":"reference/math/#clamp","text":"clamp(val, min, max) Clamps a value between a minimum and a maximum. Arguments val : number. The value to be clamped. min : number. Minimum value. max : number. Maximum value. Returns Returns val clamped between min and max . Function clamp behave as follows: if val < min , it returns min if val > max , it returns max otherwise, it returns val","title":"clamp"},{"location":"reference/math/#approximately","text":"approximately(x, y) Compares two floating point values. Since comparing two floating point numbers for equality directly may result in inaccuracies, this is a handy function. Arguments x : number. y : number. Returns Returns true if x and y are \"approximately\" equal.","title":"approximately"},{"location":"reference/math/#lerp","text":"lerp(a, b, t) Linear interpolation. Arguments a : number. b : number. t : number. A value between 0 and 1. Returns Returns the linear interpolation between a and b by t . Value t is clamped automatically to the [0, 1] range. As an example, note that lerp : returns a if t is 0 returns b if t is 1 returns (a + b) / 2 if t is 0.5","title":"lerp"},{"location":"reference/math/#smoothstep","text":"smoothstep(a, b, t) Interpolation smoothing at the limits. Arguments a : number. b : number. t : number. A value between 0 and 1. Returns Returns an interpolated value between a and b by t . Unlike lerp , smoothstep is smooth at the limits. This is useful to create smooth transitions and animations. Value t is clamped automatically to the [0, 1] range.","title":"smoothstep"},{"location":"reference/math/#lerpangle","text":"lerpAngle(alpha, beta, t) Linear interpolation of angles alpha and beta given in degrees. Unlike lerp , lerpAngle can interpolate angles when they wrap around 360 degrees. Available since: SurgeScript 0.5.4.1 Arguments alpha : number. A value in degrees. beta : number. A value in degrees. t : number. A value between 0 and 1. Returns Returns the linear interpolation between angles alpha and beta , given in degrees, by t .","title":"lerpAngle"},{"location":"reference/math/#deltaangle","text":"deltaAngle(alpha, beta) The shortest difference between angles alpha and beta given in degrees. Available since: SurgeScript 0.5.4.1 Arguments alpha : number. A value in degrees. beta : number. A value in degrees. Returns Returns, in degrees, the shortest difference between the angles.","title":"deltaAngle"},{"location":"reference/number/","text":"Number Routines for numbers. The Number object is not supposed to be used directly. The functions below are available for primitive values of the number type. Example: x = 2. toString (); // x is \"2\" t = typeof ( x ); // t is \"string\" Note: the SurgeScript Runtime stores numbers as 64-bit floating point values (following the IEEE 754 standard). Integer numbers are accurate up to 15 digits. Functions valueOf valueOf() The primitive value of the number, i.e., the number itself. Returns The number. toString toString() Converts the number to a string. Returns The number converted to a string. equals equals(x) Compares the number to another number x . This routine performs a comparison between floating point numbers. It's recommended to use Math.approximately() instead. Arguments x : number. The value to compare the number to. Returns Returns true if the numbers are equal. isFinite isFinite() Checks if the number is finite. Available since: SurgeScript 0.5.2 Returns Returns true if the number is finite. isNaN isNaN() Checks if the value is NaN (Not-a-Number). Available since: SurgeScript 0.5.2 Returns Returns true if the value is NaN. isInteger isInteger() Checks if the number is an integer. Available since: SurgeScript 0.5.2 Returns Returns true if the number is an integer.","title":"Number"},{"location":"reference/number/#number","text":"Routines for numbers. The Number object is not supposed to be used directly. The functions below are available for primitive values of the number type. Example: x = 2. toString (); // x is \"2\" t = typeof ( x ); // t is \"string\" Note: the SurgeScript Runtime stores numbers as 64-bit floating point values (following the IEEE 754 standard). Integer numbers are accurate up to 15 digits.","title":"Number"},{"location":"reference/number/#functions","text":"","title":"Functions"},{"location":"reference/number/#valueof","text":"valueOf() The primitive value of the number, i.e., the number itself. Returns The number.","title":"valueOf"},{"location":"reference/number/#tostring","text":"toString() Converts the number to a string. Returns The number converted to a string.","title":"toString"},{"location":"reference/number/#equals","text":"equals(x) Compares the number to another number x . This routine performs a comparison between floating point numbers. It's recommended to use Math.approximately() instead. Arguments x : number. The value to compare the number to. Returns Returns true if the numbers are equal.","title":"equals"},{"location":"reference/number/#isfinite","text":"isFinite() Checks if the number is finite. Available since: SurgeScript 0.5.2 Returns Returns true if the number is finite.","title":"isFinite"},{"location":"reference/number/#isnan","text":"isNaN() Checks if the value is NaN (Not-a-Number). Available since: SurgeScript 0.5.2 Returns Returns true if the value is NaN.","title":"isNaN"},{"location":"reference/number/#isinteger","text":"isInteger() Checks if the number is an integer. Available since: SurgeScript 0.5.2 Returns Returns true if the number is an integer.","title":"isInteger"},{"location":"reference/object/","text":"Object In SurgeScript, all objects are also instances of Object . This means that the properties and functions listed below are available for all objects: Properties parent parent : object, read-only. Reference to the parent object. __name __name : string, read-only. The name of the object. __active __active : boolean. Indicates whether the object is active or not. Objects are active by default. Whenever an object is set to be inactive, its state machine is paused. Additionally, the state machines of all its descendants are also paused. __functions __functions : Array object, read-only. The functions of this object represented as a collection of strings. __timespent __timespent : number, read-only. The average time spent in the current state (measured in seconds). __file __file : string, read-only. The source file of this object. Available since: SurgeScript 0.5.3 __children __children : Array object, read-only. The children of this object. Available since: SurgeScript 0.5.4 Returns A new array featuring all the children of this object. If there are no children, an empty array is returned. __childCount __childCount : number, read-only. The number of children of the object. Available since: SurgeScript 0.5.5 Note: prior to SurgeScript 0.5.5, you would use object.childCount instead. That form is now obsolete. Functions spawn spawn(objectName) Spawns an object named objectName . Arguments objectName : string. The name of the object to be spawned / instantiated. Returns A new object of the desired name. Note that the newly created object will be a child of this . destroy destroy() Destroys the object. child child(childName | childId) Looks for a child named childName (or matching childId ). Arguments childName : string. The name of the desired child. childId : number. The id of the desired child, an integer between 0 and childCount - 1 , inclusive. Returns The desired child, or null if there is no such object. children children(childName) Finds all children named childName . Since this function spawns a new array at each call, it's recommended to cache its return value. Available since: SurgeScript 0.5.4 Arguments childName : string. The name of the desired children. Returns A new array containing all children named childName . If no such children are found, an empty array is returned. childWithTag childWithTag(tagName) Finds a child tagged tagName . Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A child tagged tagName , or null if there is no such object. childrenWithTag childrenWithTag(tagName) Finds all children tagged tagName . Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A new array containing all children tagged tagName . If there are no such children, an empty array is returned. sibling sibling(siblingName) Looks for a sibling named siblingName . Two objects are siblings if they share the same parent. Arguments siblingName : string. The name of the desired sibling. Returns A sibling of name siblingName , or null if there is no such object. findObject findObject(objectName) Finds a descendant (child, grand-child, and so on) named objectName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Arguments objectName : string. The name of the desired object. Returns A descendant named objectName , or null if there is no such object. Example object \"TestObject\" { // will search for SomeOtherObject in the Application obj = Application . findObject ( \"SomeOtherObject\" ); state \"main\" { if ( obj != null ) Console . print ( \"Found the object.\" ); else Console . print ( \"Object not found.\" ); destroy (); } } findObjects findObjects(objectName) Finds all descendants named objectName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Available since: SurgeScript 0.5.4 Arguments objectName : string. The name of the objects to be found. Returns A new array containing all descendants named objectName . If no such descendants are found, an empty array is returned. findObjectWithTag findObjectWithTag(tagName) Finds a descendant tagged tagName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A descendant tagged tagName , or null if there is no such object. findObjectsWithTag findObjectsWithTag(tagName) Finds all descendants tagged tagName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A new array containing all descendants tagged tagName . If no such descendants are found, an empty array is returned. toString toString() Converts the object to a string. This function is designed to be overloaded by your own objects. Returns A string. equals equals(otherObject) Compares this object to otherObject . This function is designed to be overloaded by your own objects. Arguments otherObject : object. An object to compare this to. Returns Returns true if the objects are equal; false otherwise. hasFunction hasFunction(functionName) Checks if the object has a function named functionName . Arguments functionName : string. The name of the function. Returns Returns true if the object has a function named functionName . hasTag hasTag(tagName) Checks if the object has been tagged tagName . See also: TagSystem.hasTag() . Arguments tagName : string. The name of the tag. Returns Returns true if the object has been tagged tagName . __invoke __invoke(functionName, paramsArray) Invokes function functionName , passing the parameters specified in paramsArray . The number of elements of paramsArray must be the same as the number of parameters required by the function to be invoked. Available since: SurgeScript 0.5.2 Arguments functionName : string. The name of the function to be called. paramsArray : Array . The parameters to be passed to the function. Returns Returns the value returned by the invoked function. Example // The program below will print: // 12 // 12 // true object \"Application\" { state \"main\" { Console . print ( this . sum ( 5 , 7 )); Console . print ( this . __invoke ( \"sum\" , [ 5 , 7 ])); Console . print ( sum ( 5 , 7 ) == __invoke ( \"sum\" , [ 5 , 7 ])); Application . exit (); } fun sum ( a , b ) { return a + b ; } } __arity __arity(functionName) Returns the number of arguments of function functionName , if it's defined. If it's not defined, zero will be returned. Available since: SurgeScript 0.5.4 Arguments functionName : string. The name of a function. Returns The number of arguments of the specified function, or zero if the function is not defined.","title":"Object"},{"location":"reference/object/#object","text":"In SurgeScript, all objects are also instances of Object . This means that the properties and functions listed below are available for all objects:","title":"Object"},{"location":"reference/object/#properties","text":"","title":"Properties"},{"location":"reference/object/#parent","text":"parent : object, read-only. Reference to the parent object.","title":"parent"},{"location":"reference/object/#__name","text":"__name : string, read-only. The name of the object.","title":"__name"},{"location":"reference/object/#__active","text":"__active : boolean. Indicates whether the object is active or not. Objects are active by default. Whenever an object is set to be inactive, its state machine is paused. Additionally, the state machines of all its descendants are also paused.","title":"__active"},{"location":"reference/object/#__functions","text":"__functions : Array object, read-only. The functions of this object represented as a collection of strings.","title":"__functions"},{"location":"reference/object/#__timespent","text":"__timespent : number, read-only. The average time spent in the current state (measured in seconds).","title":"__timespent"},{"location":"reference/object/#__file","text":"__file : string, read-only. The source file of this object. Available since: SurgeScript 0.5.3","title":"__file"},{"location":"reference/object/#__children","text":"__children : Array object, read-only. The children of this object. Available since: SurgeScript 0.5.4 Returns A new array featuring all the children of this object. If there are no children, an empty array is returned.","title":"__children"},{"location":"reference/object/#__childcount","text":"__childCount : number, read-only. The number of children of the object. Available since: SurgeScript 0.5.5 Note: prior to SurgeScript 0.5.5, you would use object.childCount instead. That form is now obsolete.","title":"__childCount"},{"location":"reference/object/#functions","text":"","title":"Functions"},{"location":"reference/object/#spawn","text":"spawn(objectName) Spawns an object named objectName . Arguments objectName : string. The name of the object to be spawned / instantiated. Returns A new object of the desired name. Note that the newly created object will be a child of this .","title":"spawn"},{"location":"reference/object/#destroy","text":"destroy() Destroys the object.","title":"destroy"},{"location":"reference/object/#child","text":"child(childName | childId) Looks for a child named childName (or matching childId ). Arguments childName : string. The name of the desired child. childId : number. The id of the desired child, an integer between 0 and childCount - 1 , inclusive. Returns The desired child, or null if there is no such object.","title":"child"},{"location":"reference/object/#children","text":"children(childName) Finds all children named childName . Since this function spawns a new array at each call, it's recommended to cache its return value. Available since: SurgeScript 0.5.4 Arguments childName : string. The name of the desired children. Returns A new array containing all children named childName . If no such children are found, an empty array is returned.","title":"children"},{"location":"reference/object/#childwithtag","text":"childWithTag(tagName) Finds a child tagged tagName . Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A child tagged tagName , or null if there is no such object.","title":"childWithTag"},{"location":"reference/object/#childrenwithtag","text":"childrenWithTag(tagName) Finds all children tagged tagName . Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A new array containing all children tagged tagName . If there are no such children, an empty array is returned.","title":"childrenWithTag"},{"location":"reference/object/#sibling","text":"sibling(siblingName) Looks for a sibling named siblingName . Two objects are siblings if they share the same parent. Arguments siblingName : string. The name of the desired sibling. Returns A sibling of name siblingName , or null if there is no such object.","title":"sibling"},{"location":"reference/object/#findobject","text":"findObject(objectName) Finds a descendant (child, grand-child, and so on) named objectName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Arguments objectName : string. The name of the desired object. Returns A descendant named objectName , or null if there is no such object. Example object \"TestObject\" { // will search for SomeOtherObject in the Application obj = Application . findObject ( \"SomeOtherObject\" ); state \"main\" { if ( obj != null ) Console . print ( \"Found the object.\" ); else Console . print ( \"Object not found.\" ); destroy (); } }","title":"findObject"},{"location":"reference/object/#findobjects","text":"findObjects(objectName) Finds all descendants named objectName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Available since: SurgeScript 0.5.4 Arguments objectName : string. The name of the objects to be found. Returns A new array containing all descendants named objectName . If no such descendants are found, an empty array is returned.","title":"findObjects"},{"location":"reference/object/#findobjectwithtag","text":"findObjectWithTag(tagName) Finds a descendant tagged tagName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A descendant tagged tagName , or null if there is no such object.","title":"findObjectWithTag"},{"location":"reference/object/#findobjectswithtag","text":"findObjectsWithTag(tagName) Finds all descendants tagged tagName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A new array containing all descendants tagged tagName . If no such descendants are found, an empty array is returned.","title":"findObjectsWithTag"},{"location":"reference/object/#tostring","text":"toString() Converts the object to a string. This function is designed to be overloaded by your own objects. Returns A string.","title":"toString"},{"location":"reference/object/#equals","text":"equals(otherObject) Compares this object to otherObject . This function is designed to be overloaded by your own objects. Arguments otherObject : object. An object to compare this to. Returns Returns true if the objects are equal; false otherwise.","title":"equals"},{"location":"reference/object/#hasfunction","text":"hasFunction(functionName) Checks if the object has a function named functionName . Arguments functionName : string. The name of the function. Returns Returns true if the object has a function named functionName .","title":"hasFunction"},{"location":"reference/object/#hastag","text":"hasTag(tagName) Checks if the object has been tagged tagName . See also: TagSystem.hasTag() . Arguments tagName : string. The name of the tag. Returns Returns true if the object has been tagged tagName .","title":"hasTag"},{"location":"reference/object/#__invoke","text":"__invoke(functionName, paramsArray) Invokes function functionName , passing the parameters specified in paramsArray . The number of elements of paramsArray must be the same as the number of parameters required by the function to be invoked. Available since: SurgeScript 0.5.2 Arguments functionName : string. The name of the function to be called. paramsArray : Array . The parameters to be passed to the function. Returns Returns the value returned by the invoked function. Example // The program below will print: // 12 // 12 // true object \"Application\" { state \"main\" { Console . print ( this . sum ( 5 , 7 )); Console . print ( this . __invoke ( \"sum\" , [ 5 , 7 ])); Console . print ( sum ( 5 , 7 ) == __invoke ( \"sum\" , [ 5 , 7 ])); Application . exit (); } fun sum ( a , b ) { return a + b ; } }","title":"__invoke"},{"location":"reference/object/#__arity","text":"__arity(functionName) Returns the number of arguments of function functionName , if it's defined. If it's not defined, zero will be returned. Available since: SurgeScript 0.5.4 Arguments functionName : string. The name of a function. Returns The number of arguments of the specified function, or zero if the function is not defined.","title":"__arity"},{"location":"reference/plugin/","text":"Plugin SurgeScript features a plugin system that allows you to extend the functionalities of the language. Known as plugins or packages , these objects can be imported and accessed anywhere in the code. They are imported using a using statement. The plugin system can be accessed simply by typing Plugin . Example: // File: app.ss // An application that uses StringUtils, defined in another file using StringUtils ; object \"Application\" { str = \"alucard\" ; state \"main\" { Console . print ( \"Reverse a string:\" ); Console . print ( str ); Console . print ( StringUtils . reverse ( str )); Application . exit (); } } // File: string_utils.ss // String utilities @Package object \"StringUtils\" { fun reverse ( str ) { buf = \"\" ; for ( i = str . length - 1 ; i >= 0 ; i --) buf += str [ i ]; return buf ; } } Available since: SurgeScript 0.5.2 Properties count count : number, read-only. The number of plugins. Functions spawn spawn(objectName) Spawns an object called objectName as a plugin. This function is not to be used directly, as SurgeScript spawns the plugins automatically for you. Arguments objectName : string. The name of the object to be spawned as a plugin. It's not recommended to include special characters in this name. get get(objectName) Gets a reference to the plugin named objectName . The [ ] operator can be used instead of the get() function, as in Plugin[objectName] . Rather than using this function, it's recommended to import the desired object using the using MyObject; statement at the beginning of your code. Your object will be available as MyObject . Arguments objectName : string. The name of the plugin. Example using StringUtils ; // ... assert ( Plugin [ \"StringUtils\" ] === StringUtils ); assert ( Plugin . StringUtils === StringUtils );","title":"Plugin"},{"location":"reference/plugin/#plugin","text":"SurgeScript features a plugin system that allows you to extend the functionalities of the language. Known as plugins or packages , these objects can be imported and accessed anywhere in the code. They are imported using a using statement. The plugin system can be accessed simply by typing Plugin . Example: // File: app.ss // An application that uses StringUtils, defined in another file using StringUtils ; object \"Application\" { str = \"alucard\" ; state \"main\" { Console . print ( \"Reverse a string:\" ); Console . print ( str ); Console . print ( StringUtils . reverse ( str )); Application . exit (); } } // File: string_utils.ss // String utilities @Package object \"StringUtils\" { fun reverse ( str ) { buf = \"\" ; for ( i = str . length - 1 ; i >= 0 ; i --) buf += str [ i ]; return buf ; } } Available since: SurgeScript 0.5.2","title":"Plugin"},{"location":"reference/plugin/#properties","text":"","title":"Properties"},{"location":"reference/plugin/#count","text":"count : number, read-only. The number of plugins.","title":"count"},{"location":"reference/plugin/#functions","text":"","title":"Functions"},{"location":"reference/plugin/#spawn","text":"spawn(objectName) Spawns an object called objectName as a plugin. This function is not to be used directly, as SurgeScript spawns the plugins automatically for you. Arguments objectName : string. The name of the object to be spawned as a plugin. It's not recommended to include special characters in this name.","title":"spawn"},{"location":"reference/plugin/#get","text":"get(objectName) Gets a reference to the plugin named objectName . The [ ] operator can be used instead of the get() function, as in Plugin[objectName] . Rather than using this function, it's recommended to import the desired object using the using MyObject; statement at the beginning of your code. Your object will be available as MyObject . Arguments objectName : string. The name of the plugin. Example using StringUtils ; // ... assert ( Plugin [ \"StringUtils\" ] === StringUtils ); assert ( Plugin . StringUtils === StringUtils );","title":"get"},{"location":"reference/string/","text":"String Routines for strings. The String object is not supposed to be used directly (generally speaking). The functions below are available for primitive values of the string type. Example: // Useful string routines x = \"SurgeScript\" . toLowerCase (); // \"surgescript\" y = x . substr ( 0 , 5 ); // \"surge\" z = x [ 0 ]; // \"s\" (first character of x) n = y . length ; // 5 Strings in SurgeScript are immutable. Once a string is set, its individual characters cannot be changed. If you need to modify the content of a string, reassign the variable to a new string. Static functions isNullOrEmpty isNullOrEmpty(value) Checks if the given value is either null or an empty string ( \"\" ). Available since: SurgeScript 0.5.3 Arguments value : string | null . The value to be tested. Returns Returns true if value is either null or an empty string. Example name = \"Surge\" ; //name = \"\"; //name = null; if (! String . isNullOrEmpty ( name )) Console . print ( name ); Properties length length : number, read-only. The length of the string. Functions valueOf valueOf() The primitive value of the string, i.e., the string itself. Returns The string. toString toString() Convert to string. Returns The string itself. equals equals(str) Compares the string to another string str . Arguments str : string. Returns Returns true if the strings are equal. get get(i) Gets the i -th character of the string. The [ ] operator can be used equivalently. Arguments i : integer number. A value between 0 (inclusive) and the length of the string (exclusive). Returns The i -th character of the string (0-based index). indexOf indexOf(str) Finds the position of the first occurrence of str in the string. Arguments str : string. The string to be searched for. Returns The position (0-based index) of the first occurrence of str in the string, or -1 if there is no such occurrence. Example name = \"SurgeScript\" ; a = name . indexOf ( \"Surge\" ); // a is 0 b = name . indexOf ( \"Neon\" ); // b is -1 c = name . indexOf ( \"e\" ); // c is 4 d = name . indexOf ( \"script\" ); // d is -1, as the search is case-sensitive substr substr(start, length) Extracts the substring starting at position start with length length . Arguments start : number. The start position. The beginning of the string is at position 0. length : number. The length of the substring. Returns The substring with length length starting at start . Example name = \"SurgeScript\" ; surge = name . substr ( 0 , 5 ); // \"Surge\" script = name . substr ( 5 , 6 ); // \"Script\" e = name . substr ( 4 , 1 ); // \"e\" empty = name . substr ( 555 , 1 ); // \"\" concat concat(str) Concatenates two strings. This is the same as using the + operator. Arguments str : string. Returns The caller string concatenated with str at the end. Example name = \"Surge\" . concat ( \"Script\" ); // SurgeScript name = \"Surge\" + \"Script\" ; // SurgeScript replace replace(oldstr, newstr) Replaces all occurrences of oldstr to newstr in the caller string. Arguments oldstr : string. The substring to be replaced. newstr : string. The substring that should appear in the result. Returns The caller string having all its occurrences of oldstr replaced to newstr . Example // dst is \"Gimacian, Neon and Charge\" src = \"Surge, Neon and Charge\" ; dst = src . replace ( \"Surge\" , \"Gimacian\" ); toLowerCase toLowerCase() Converts the string to lower case. Returns The string converted to lower case. toUpperCase toUpperCase() Converts the string to upper case. Returns The string converted to upper case.","title":"String"},{"location":"reference/string/#string","text":"Routines for strings. The String object is not supposed to be used directly (generally speaking). The functions below are available for primitive values of the string type. Example: // Useful string routines x = \"SurgeScript\" . toLowerCase (); // \"surgescript\" y = x . substr ( 0 , 5 ); // \"surge\" z = x [ 0 ]; // \"s\" (first character of x) n = y . length ; // 5 Strings in SurgeScript are immutable. Once a string is set, its individual characters cannot be changed. If you need to modify the content of a string, reassign the variable to a new string.","title":"String"},{"location":"reference/string/#static-functions","text":"","title":"Static functions"},{"location":"reference/string/#isnullorempty","text":"isNullOrEmpty(value) Checks if the given value is either null or an empty string ( \"\" ). Available since: SurgeScript 0.5.3 Arguments value : string | null . The value to be tested. Returns Returns true if value is either null or an empty string. Example name = \"Surge\" ; //name = \"\"; //name = null; if (! String . isNullOrEmpty ( name )) Console . print ( name );","title":"isNullOrEmpty"},{"location":"reference/string/#properties","text":"","title":"Properties"},{"location":"reference/string/#length","text":"length : number, read-only. The length of the string.","title":"length"},{"location":"reference/string/#functions","text":"","title":"Functions"},{"location":"reference/string/#valueof","text":"valueOf() The primitive value of the string, i.e., the string itself. Returns The string.","title":"valueOf"},{"location":"reference/string/#tostring","text":"toString() Convert to string. Returns The string itself.","title":"toString"},{"location":"reference/string/#equals","text":"equals(str) Compares the string to another string str . Arguments str : string. Returns Returns true if the strings are equal.","title":"equals"},{"location":"reference/string/#get","text":"get(i) Gets the i -th character of the string. The [ ] operator can be used equivalently. Arguments i : integer number. A value between 0 (inclusive) and the length of the string (exclusive). Returns The i -th character of the string (0-based index).","title":"get"},{"location":"reference/string/#indexof","text":"indexOf(str) Finds the position of the first occurrence of str in the string. Arguments str : string. The string to be searched for. Returns The position (0-based index) of the first occurrence of str in the string, or -1 if there is no such occurrence. Example name = \"SurgeScript\" ; a = name . indexOf ( \"Surge\" ); // a is 0 b = name . indexOf ( \"Neon\" ); // b is -1 c = name . indexOf ( \"e\" ); // c is 4 d = name . indexOf ( \"script\" ); // d is -1, as the search is case-sensitive","title":"indexOf"},{"location":"reference/string/#substr","text":"substr(start, length) Extracts the substring starting at position start with length length . Arguments start : number. The start position. The beginning of the string is at position 0. length : number. The length of the substring. Returns The substring with length length starting at start . Example name = \"SurgeScript\" ; surge = name . substr ( 0 , 5 ); // \"Surge\" script = name . substr ( 5 , 6 ); // \"Script\" e = name . substr ( 4 , 1 ); // \"e\" empty = name . substr ( 555 , 1 ); // \"\"","title":"substr"},{"location":"reference/string/#concat","text":"concat(str) Concatenates two strings. This is the same as using the + operator. Arguments str : string. Returns The caller string concatenated with str at the end. Example name = \"Surge\" . concat ( \"Script\" ); // SurgeScript name = \"Surge\" + \"Script\" ; // SurgeScript","title":"concat"},{"location":"reference/string/#replace","text":"replace(oldstr, newstr) Replaces all occurrences of oldstr to newstr in the caller string. Arguments oldstr : string. The substring to be replaced. newstr : string. The substring that should appear in the result. Returns The caller string having all its occurrences of oldstr replaced to newstr . Example // dst is \"Gimacian, Neon and Charge\" src = \"Surge, Neon and Charge\" ; dst = src . replace ( \"Surge\" , \"Gimacian\" );","title":"replace"},{"location":"reference/string/#tolowercase","text":"toLowerCase() Converts the string to lower case. Returns The string converted to lower case.","title":"toLowerCase"},{"location":"reference/string/#touppercase","text":"toUpperCase() Converts the string to upper case. Returns The string converted to upper case.","title":"toUpperCase"},{"location":"reference/surgescript/","text":"SurgeScript Data related to the scripting language itself. You can access this object simply by typing SurgeScript . Example: // Prints the version of the SurgeScript runtime object \"Application\" { state \"main\" { Console . print ( SurgeScript . version ); } } Available since: SurgeScript 0.5.2 Properties version version : string, read-only. Version number of the SurgeScript runtime.","title":"SurgeScript"},{"location":"reference/surgescript/#surgescript","text":"Data related to the scripting language itself. You can access this object simply by typing SurgeScript . Example: // Prints the version of the SurgeScript runtime object \"Application\" { state \"main\" { Console . print ( SurgeScript . version ); } } Available since: SurgeScript 0.5.2","title":"SurgeScript"},{"location":"reference/surgescript/#properties","text":"","title":"Properties"},{"location":"reference/surgescript/#version","text":"version : string, read-only. Version number of the SurgeScript runtime.","title":"version"},{"location":"reference/system/","text":"System The root object. Used to gather data from the language and to access special objects. It can be accessed by typing System . Properties tags tags : Tag System object, read-only. A reference to the Tag System. gc gc : Garbage Collector object, read-only. A reference to the Garbage Collector object. objectCount objectCount : number, read-only. The total number of objects at this moment. Functions exit exit() Exits the Application. destroy destroy() The same as exit() .","title":"System"},{"location":"reference/system/#system","text":"The root object. Used to gather data from the language and to access special objects. It can be accessed by typing System .","title":"System"},{"location":"reference/system/#properties","text":"","title":"Properties"},{"location":"reference/system/#tags","text":"tags : Tag System object, read-only. A reference to the Tag System.","title":"tags"},{"location":"reference/system/#gc","text":"gc : Garbage Collector object, read-only. A reference to the Garbage Collector object.","title":"gc"},{"location":"reference/system/#objectcount","text":"objectCount : number, read-only. The total number of objects at this moment.","title":"objectCount"},{"location":"reference/system/#functions","text":"","title":"Functions"},{"location":"reference/system/#exit","text":"exit() Exits the Application.","title":"exit"},{"location":"reference/system/#destroy","text":"destroy() The same as exit() .","title":"destroy"},{"location":"reference/tags/","text":"TagSystem Utility functions for dealing with object tags. This object is available at System.tags and shouldn't be instantiated directly. Functions list list() Lists all tags used in all objects. Returns A new Array of strings with all tags used in all objects. select select(tagName) Selects all objects that are tagged tagName . Arguments tagName : string. Returns A new Array of strings with the names of the objects tagged with tagName . If there are no such objects, an empty array is returned. tagsOf tagsOf(objectName) Returns the tags of the objects named objectName . Available since: SurgeScript 0.6.0 Arguments objectName : string. Returns A new Array of strings with the names of the tags associated with the objects named objectName . If the objects are untagged or do not exist, an empty array is returned. hasTag hasTag(objectName, tagName) Checks if objects named objectName are tagged tagName . Prefer using Object.hasTag() if possible. See also: Object.hasTag() . Available since: SurgeScript 0.6.0 Arguments objectName : string. tagName : string. Returns Returns true if the objects are tagged as specified, or false otherwise.","title":"TagSystem"},{"location":"reference/tags/#tagsystem","text":"Utility functions for dealing with object tags. This object is available at System.tags and shouldn't be instantiated directly.","title":"TagSystem"},{"location":"reference/tags/#functions","text":"","title":"Functions"},{"location":"reference/tags/#list","text":"list() Lists all tags used in all objects. Returns A new Array of strings with all tags used in all objects.","title":"list"},{"location":"reference/tags/#select","text":"select(tagName) Selects all objects that are tagged tagName . Arguments tagName : string. Returns A new Array of strings with the names of the objects tagged with tagName . If there are no such objects, an empty array is returned.","title":"select"},{"location":"reference/tags/#tagsof","text":"tagsOf(objectName) Returns the tags of the objects named objectName . Available since: SurgeScript 0.6.0 Arguments objectName : string. Returns A new Array of strings with the names of the tags associated with the objects named objectName . If the objects are untagged or do not exist, an empty array is returned.","title":"tagsOf"},{"location":"reference/tags/#hastag","text":"hasTag(objectName, tagName) Checks if objects named objectName are tagged tagName . Prefer using Object.hasTag() if possible. See also: Object.hasTag() . Available since: SurgeScript 0.6.0 Arguments objectName : string. tagName : string. Returns Returns true if the objects are tagged as specified, or false otherwise.","title":"hasTag"},{"location":"reference/time/","text":"Time Time utilities. This object is available simply by typing Time . Properties time time : number, read-only. Elapsed time, in seconds, since the application was started and measured at the beginning of the current frame. delta delta : number, read-only. The time, in seconds, taken to complete the last frame of the application. Use this value to make your application behave consistently regardless of the frame rate. now now : number, read-only. Elapsed time, in seconds, since the application was started and measured at the moment this property is evaluated. Available since: SurgeScript 0.5.4 Tip It's generally advisable to use Time.time instead, because Time.now may return different values in the same frame of your application.","title":"Time"},{"location":"reference/time/#time","text":"Time utilities. This object is available simply by typing Time .","title":"Time"},{"location":"reference/time/#properties","text":"","title":"Properties"},{"location":"reference/time/#time_1","text":"time : number, read-only. Elapsed time, in seconds, since the application was started and measured at the beginning of the current frame.","title":"time"},{"location":"reference/time/#delta","text":"delta : number, read-only. The time, in seconds, taken to complete the last frame of the application. Use this value to make your application behave consistently regardless of the frame rate.","title":"delta"},{"location":"reference/time/#now","text":"now : number, read-only. Elapsed time, in seconds, since the application was started and measured at the moment this property is evaluated. Available since: SurgeScript 0.5.4 Tip It's generally advisable to use Time.time instead, because Time.now may return different values in the same frame of your application.","title":"now"},{"location":"tutorials/advanced_features/","text":"Advanced features This section describes advanced features of SurgeScript. Lookup operator Some programming languages, such as C++, have a feature called operator overloading . It's a syntactic sugar that allows the programmer to attribute custom implementations to different operators. In SurgeScript, the [] operator (also called the lookup operator ), used by Arrays and Dictionaries , is used to get and set values from/to the data structure. In fact, the [] operator can be used with any object. It is necessary to define, in your object, functions named get() and set() with the following signature: fun get ( key ) { // custom implementation } fun set ( key , value ) { // custom implementation } Given an object obj , the expression x = obj[key] is equivalent to x = obj.get(key) . Similarly, obj[key] = value is equivalent to obj.set(key, value) . Function objects In SurgeScript, objects can be made to behave like functions. We call these objects function objects (or functors ). To make an object behave like a function, you have to overload the () operator (also known as the function operator ). This is done by defining function call() in your object: fun call () { // custom implementation } Function call() may take any number of parameters. Given an object f , the expression y = f(x) is equivalent to y = f.call(x) . Notice that, since f is an object, you may exchange its implementation during runtime. Assertions The assert(condition) statement specifies a condition that you expect to be true at a certain point in your code. If that condition turns out to be false, the code will be interrupted with an assertion failed error. Example: assert ( name == \"Surge\" ); // will crash if name isn't \"Surge\" Chaining In SurgeScript, it's possible to configure objects in an elegant way using a technique called chaining . Consider the object below - it simply displays a message at regular intervals: object \"Parrot\" { message = \"I am a Parrot\" ; state \"main\" { if ( timeout ( 1.0 )) state = \"print\" ; } state \"print\" { Console . print ( message ); state = \"main\" ; } // Note that this function returns // this, i.e., the object itself. fun setMessage ( newMessage ) { message = newMessage ; return this ; } } Suppose that, in your Application, you would like to spawn that object and modify its message. One way of doing it would be making its internal variable public and changing its contents in the constructor function of your Application. A more concise and elegant way of doing it would be calling function setMessage() just after you spawn the object: object \"Application\" { parrot = spawn ( \"Parrot\" ). setMessage ( \"Hello!\" ); state \"main\" { } } Observe that the function we have defined does two things: It modifies the internals of the object in some way It always returns this (that is, the object itself) We call that function a chainable function . You may call such a function from your Application, just after spawn() , and you'll still have a reference to the spawned object. Moreover, since chainable functions always return this , you may chain multiple function calls into a single statement, making your code concise and your statement descriptive. Example: parrot = spawn ( \"Parrot\" ). setMessage ( \"Hello!\" ). setInterval ( 2.0 ); Factory In SurgeScript, a factory is a functor that spawns an object for you. The object can be spawned and configured in a single call. In the example below, factory Greeter spawns and configures Greeting objects. We annotate the factory with @Package , so it can be imported anywhere in the code. To the end-user, calling Greeter() is simpler than manually spawning and configuring a Greeting every time it is needed. // Factory example using Greeter ; // import the factory object \"Application\" { state \"main\" { // This will print: // Hello, alex! g = Greeter ( \"alex\" ); g . greet (); exit (); } } // File: greeting.ss object \"Greeting\" { public name = \"anon\" ; fun greet () { Console . print ( \"Hello, \" + name + \"!\" ); } } @Package object \"Greeter\" { // Greeter is a factory. It spawns and configures // a Greeting object for you. As it is a package, // it can be imported and used anywhere. fun call ( name ) { g = spawn ( \"Greeting\" ); g . name = name ; return g ; } } In the example above, objects spawned by the factory will be children of the factory. If you need the parent of the spawned object to be the caller, simply write g = caller.spawn(\"Greeter\") . Know that caller points to the object that called the function (or null if not applicable). Iterators As seen in the loops section, the foreach loop may be used to iterate through an iterable collection. In SurgeScript, an iterable collection is an object that implements the iterator protocol described below. You may implement your own iterable collections by tagging them as \"iterable\" and implementing function iterator() . If you have ever used Java, you'll find this to be familiar. // Iterable collections are tagged \"iterable\" // and implement function iterator() object \"MyCollection\" is \"iterable\" { fun iterator () { // function iterator() takes no arguments and // returns a new iterator object } } For each iterable collection you define, you must define its iterator object. The iterator object must be tagged \"iterator\" and implement functions next() and hasNext() (both take no arguments): // Iterators are tagged \"iterator\" and // implement functions next() and hasNext() object \"MyIterator\" is \"iterator\" { fun next () { // returns the next element of the collection // and advances the iteration pointer // the iterable collection is usually the parent // object, i.e., collection = parent } function hasNext () { // returns true if the enumeration isn't over // returns false if there are no more elements } } You may iterate over an iterable collection using the following code: it = collection . iterator (); while ( it . hasNext ()) { x = it . next (); // do something with x // x is an element of the collection Console . print ( x ); } Or, alternatively, using the compact foreach: foreach ( x in collection ) { Console . print ( x ); } For the sake of completion, the following code demonstrates how to implement a custom iterable collection that hold even numbers from 0 up to 20 without having to store them explicitly in memory: object \"Application\" { evenNumbers = spawn ( \"Even Numbers\" ). upTo ( 20 ); state \"main\" { // print all the numbers of the iterable collection foreach ( number in evenNumbers ) Console . print ( number ); // we're done! exit (); } } object \"Even Numbers\" is \"iterable\" { lastNumber = 0 ; fun iterator () { return spawn ( \"Even Numbers Iterator\" ). upTo ( lastNumber ); } fun upTo ( num ) { // upTo() is a chainable function that // is NOT part of the iterator protocol // (but it's useful for this example) lastNumber = Number ( num ); return this ; } } object \"Even Numbers Iterator\" is \"iterator\" { nextNumber = 0 ; lastNumber = 0 ; fun next () { currentNumber = nextNumber ; nextNumber += 2 ; return currentNumber ; } fun hasNext () { return nextNumber <= lastNumber ; } fun upTo ( num ) { // upTo() is a chainable function that // is NOT part of the iterator protocol // (but it's useful for this example) lastNumber = Number ( num ); return this ; } } The output of this code is: 0 2 4 6 8 10 12 14 16 18 20 Challenge! Can you write an iterable collection called Fibonacci Sequence containing the first N Fibonacci numbers without storing them all explicitly in memory? It should be used as follows: // Desired output (for N=10): 0 1 1 2 3 5 8 13 21 34 sequence = spawn ( \"Fibonacci Sequence\" ). ofLength ( 10 ); foreach ( number in sequence ) Console . print ( number );","title":"Advanced features"},{"location":"tutorials/advanced_features/#advanced-features","text":"This section describes advanced features of SurgeScript.","title":"Advanced features"},{"location":"tutorials/advanced_features/#lookup-operator","text":"Some programming languages, such as C++, have a feature called operator overloading . It's a syntactic sugar that allows the programmer to attribute custom implementations to different operators. In SurgeScript, the [] operator (also called the lookup operator ), used by Arrays and Dictionaries , is used to get and set values from/to the data structure. In fact, the [] operator can be used with any object. It is necessary to define, in your object, functions named get() and set() with the following signature: fun get ( key ) { // custom implementation } fun set ( key , value ) { // custom implementation } Given an object obj , the expression x = obj[key] is equivalent to x = obj.get(key) . Similarly, obj[key] = value is equivalent to obj.set(key, value) .","title":"Lookup operator"},{"location":"tutorials/advanced_features/#function-objects","text":"In SurgeScript, objects can be made to behave like functions. We call these objects function objects (or functors ). To make an object behave like a function, you have to overload the () operator (also known as the function operator ). This is done by defining function call() in your object: fun call () { // custom implementation } Function call() may take any number of parameters. Given an object f , the expression y = f(x) is equivalent to y = f.call(x) . Notice that, since f is an object, you may exchange its implementation during runtime.","title":"Function objects"},{"location":"tutorials/advanced_features/#assertions","text":"The assert(condition) statement specifies a condition that you expect to be true at a certain point in your code. If that condition turns out to be false, the code will be interrupted with an assertion failed error. Example: assert ( name == \"Surge\" ); // will crash if name isn't \"Surge\"","title":"Assertions"},{"location":"tutorials/advanced_features/#chaining","text":"In SurgeScript, it's possible to configure objects in an elegant way using a technique called chaining . Consider the object below - it simply displays a message at regular intervals: object \"Parrot\" { message = \"I am a Parrot\" ; state \"main\" { if ( timeout ( 1.0 )) state = \"print\" ; } state \"print\" { Console . print ( message ); state = \"main\" ; } // Note that this function returns // this, i.e., the object itself. fun setMessage ( newMessage ) { message = newMessage ; return this ; } } Suppose that, in your Application, you would like to spawn that object and modify its message. One way of doing it would be making its internal variable public and changing its contents in the constructor function of your Application. A more concise and elegant way of doing it would be calling function setMessage() just after you spawn the object: object \"Application\" { parrot = spawn ( \"Parrot\" ). setMessage ( \"Hello!\" ); state \"main\" { } } Observe that the function we have defined does two things: It modifies the internals of the object in some way It always returns this (that is, the object itself) We call that function a chainable function . You may call such a function from your Application, just after spawn() , and you'll still have a reference to the spawned object. Moreover, since chainable functions always return this , you may chain multiple function calls into a single statement, making your code concise and your statement descriptive. Example: parrot = spawn ( \"Parrot\" ). setMessage ( \"Hello!\" ). setInterval ( 2.0 );","title":"Chaining"},{"location":"tutorials/advanced_features/#factory","text":"In SurgeScript, a factory is a functor that spawns an object for you. The object can be spawned and configured in a single call. In the example below, factory Greeter spawns and configures Greeting objects. We annotate the factory with @Package , so it can be imported anywhere in the code. To the end-user, calling Greeter() is simpler than manually spawning and configuring a Greeting every time it is needed. // Factory example using Greeter ; // import the factory object \"Application\" { state \"main\" { // This will print: // Hello, alex! g = Greeter ( \"alex\" ); g . greet (); exit (); } } // File: greeting.ss object \"Greeting\" { public name = \"anon\" ; fun greet () { Console . print ( \"Hello, \" + name + \"!\" ); } } @Package object \"Greeter\" { // Greeter is a factory. It spawns and configures // a Greeting object for you. As it is a package, // it can be imported and used anywhere. fun call ( name ) { g = spawn ( \"Greeting\" ); g . name = name ; return g ; } } In the example above, objects spawned by the factory will be children of the factory. If you need the parent of the spawned object to be the caller, simply write g = caller.spawn(\"Greeter\") . Know that caller points to the object that called the function (or null if not applicable).","title":"Factory"},{"location":"tutorials/advanced_features/#iterators","text":"As seen in the loops section, the foreach loop may be used to iterate through an iterable collection. In SurgeScript, an iterable collection is an object that implements the iterator protocol described below. You may implement your own iterable collections by tagging them as \"iterable\" and implementing function iterator() . If you have ever used Java, you'll find this to be familiar. // Iterable collections are tagged \"iterable\" // and implement function iterator() object \"MyCollection\" is \"iterable\" { fun iterator () { // function iterator() takes no arguments and // returns a new iterator object } } For each iterable collection you define, you must define its iterator object. The iterator object must be tagged \"iterator\" and implement functions next() and hasNext() (both take no arguments): // Iterators are tagged \"iterator\" and // implement functions next() and hasNext() object \"MyIterator\" is \"iterator\" { fun next () { // returns the next element of the collection // and advances the iteration pointer // the iterable collection is usually the parent // object, i.e., collection = parent } function hasNext () { // returns true if the enumeration isn't over // returns false if there are no more elements } } You may iterate over an iterable collection using the following code: it = collection . iterator (); while ( it . hasNext ()) { x = it . next (); // do something with x // x is an element of the collection Console . print ( x ); } Or, alternatively, using the compact foreach: foreach ( x in collection ) { Console . print ( x ); } For the sake of completion, the following code demonstrates how to implement a custom iterable collection that hold even numbers from 0 up to 20 without having to store them explicitly in memory: object \"Application\" { evenNumbers = spawn ( \"Even Numbers\" ). upTo ( 20 ); state \"main\" { // print all the numbers of the iterable collection foreach ( number in evenNumbers ) Console . print ( number ); // we're done! exit (); } } object \"Even Numbers\" is \"iterable\" { lastNumber = 0 ; fun iterator () { return spawn ( \"Even Numbers Iterator\" ). upTo ( lastNumber ); } fun upTo ( num ) { // upTo() is a chainable function that // is NOT part of the iterator protocol // (but it's useful for this example) lastNumber = Number ( num ); return this ; } } object \"Even Numbers Iterator\" is \"iterator\" { nextNumber = 0 ; lastNumber = 0 ; fun next () { currentNumber = nextNumber ; nextNumber += 2 ; return currentNumber ; } fun hasNext () { return nextNumber <= lastNumber ; } fun upTo ( num ) { // upTo() is a chainable function that // is NOT part of the iterator protocol // (but it's useful for this example) lastNumber = Number ( num ); return this ; } } The output of this code is: 0 2 4 6 8 10 12 14 16 18 20 Challenge! Can you write an iterable collection called Fibonacci Sequence containing the first N Fibonacci numbers without storing them all explicitly in memory? It should be used as follows: // Desired output (for N=10): 0 1 1 2 3 5 8 13 21 34 sequence = spawn ( \"Fibonacci Sequence\" ). ofLength ( 10 ); foreach ( number in sequence ) Console . print ( number );","title":"Iterators"},{"location":"tutorials/best_practices/","text":"Best Practices Read the Components section. It's crucial that you understand it. Follow the golden rule: objects should not mess with each others' internals! Objects should not change others' internal variables or states directly (not allowed!) Objects should define functions that can be operated upon by the external world (API) Use a consistent coding style. Suggestion: Use camelCase names for both variables and functions. Use 4 spaces when indenting your code. Combine related packages into a single one: don't pollute the global namespace. Read the SurgeScript documentation often. Practice, practice, practice! - and have fun!","title":"Best practices"},{"location":"tutorials/best_practices/#best-practices","text":"Read the Components section. It's crucial that you understand it. Follow the golden rule: objects should not mess with each others' internals! Objects should not change others' internal variables or states directly (not allowed!) Objects should define functions that can be operated upon by the external world (API) Use a consistent coding style. Suggestion: Use camelCase names for both variables and functions. Use 4 spaces when indenting your code. Combine related packages into a single one: don't pollute the global namespace. Read the SurgeScript documentation often. Practice, practice, practice! - and have fun!","title":"Best Practices"},{"location":"tutorials/comments/","text":"Comments Comments are used to make your code more human-readable. They are ignored by the computer. SurgeScript allows two kinds of comments: single-line comments and multi-line comments. Single-line comments Single-line comments start with a // . Example: // This line has no effect on the code (it's just for improved readability) x = 3 + 4 ; // x is now 7 Multi-line comments Multi-line comments start with a /* and end with a */ . Example: /* * Comments can, but don't have to, take * multiple lines if you use this form. */ x = 3 + 4 ; /* x is now 7 */ Comments of this form cannot be nested.","title":"Comments"},{"location":"tutorials/comments/#comments","text":"Comments are used to make your code more human-readable. They are ignored by the computer. SurgeScript allows two kinds of comments: single-line comments and multi-line comments.","title":"Comments"},{"location":"tutorials/comments/#single-line-comments","text":"Single-line comments start with a // . Example: // This line has no effect on the code (it's just for improved readability) x = 3 + 4 ; // x is now 7","title":"Single-line comments"},{"location":"tutorials/comments/#multi-line-comments","text":"Multi-line comments start with a /* and end with a */ . Example: /* * Comments can, but don't have to, take * multiple lines if you use this form. */ x = 3 + 4 ; /* x is now 7 */ Comments of this form cannot be nested.","title":"Multi-line comments"},{"location":"tutorials/components/","text":"Components Introduction Entity Component System (ECS) is a software pattern used in game development. The idea is that in-game objects (called entities ) can be customized by adding or removing objects (called components ) during runtime. Components add functionalities or behaviors to the entities to which they are attached to. In SurgeScript, both entities and components are objects - the difference is conceptual. As an example, consider an in-game object called Parrot . Objects by themselves are empty; they do nothing. However, an interesting behavior of parrots is that they are blabbers: they keep repeating the same thing over and over again. So, let's create an empty object called Parrot , tag it as an entity and spawn the Blabber component on it: object \"Parrot\" is \"entity\" { blabber = spawn ( \"Blabber\" ); state \"main\" { } } object \"Blabber\" { state \"main\" { if ( timeout ( 2 )) // blab every 2 seconds state = \"blab\" ; } state \"blab\" { Console . print ( \"Hello!\" ); state = \"main\" ; } } Now, whenever you spawn a Parrot, it will keep blabbing ( parroting ) unceasingly: Hello! Hello! Hello! ... Suppose now that your Parrot is a Kamikaze Robot: it blabs so much that it will explode itself after some time. We'll attach a Time Bomb to the parroting robot, so that it will stop blabbing after a while: object \"Time Bomb\" { state \"main\" { if ( timeout ( 15 )) // explode after 15 seconds state = \"explode\" ; } state \"explode\" { Console . print ( \"BOOOM!\" ); parent . destroy (); // destroy the parent object } } object \"Parrot\" is \"entity\" { blabber = spawn ( \"Blabber\" ); bomb = spawn ( \"Time Bomb\" ); state \"main\" { } } Now, here's the output: Hello! Hello! Hello! Hello! Hello! Hello! Hello! BOOOM! In this example, Parrot is an entity and Blabber and Time Bomb are its components. Once the entity is destroyed, its components (its children) are also destroyed automatically. Design considerations In some implementations of ECS, entities are implemented as integers and components consist of raw data only. The game logic is executed by the System layer, which iterates throughout all entities continuously and executes the logic according to the components attached to them. In SurgeScript, components execute their own code and can be attached to entities simply by spawning them as children. Still, you can use the former approach if you wish to do so. Composition over inheritance SurgeScript does not explicitly support inheritance, a feature found in other object-oriented languages. The usage of components is encouraged instead. SurgeScript favors composition over inheritance, allowing for greater flexibility when defining in-game objects.","title":"Components"},{"location":"tutorials/components/#components","text":"","title":"Components"},{"location":"tutorials/components/#introduction","text":"Entity Component System (ECS) is a software pattern used in game development. The idea is that in-game objects (called entities ) can be customized by adding or removing objects (called components ) during runtime. Components add functionalities or behaviors to the entities to which they are attached to. In SurgeScript, both entities and components are objects - the difference is conceptual. As an example, consider an in-game object called Parrot . Objects by themselves are empty; they do nothing. However, an interesting behavior of parrots is that they are blabbers: they keep repeating the same thing over and over again. So, let's create an empty object called Parrot , tag it as an entity and spawn the Blabber component on it: object \"Parrot\" is \"entity\" { blabber = spawn ( \"Blabber\" ); state \"main\" { } } object \"Blabber\" { state \"main\" { if ( timeout ( 2 )) // blab every 2 seconds state = \"blab\" ; } state \"blab\" { Console . print ( \"Hello!\" ); state = \"main\" ; } } Now, whenever you spawn a Parrot, it will keep blabbing ( parroting ) unceasingly: Hello! Hello! Hello! ... Suppose now that your Parrot is a Kamikaze Robot: it blabs so much that it will explode itself after some time. We'll attach a Time Bomb to the parroting robot, so that it will stop blabbing after a while: object \"Time Bomb\" { state \"main\" { if ( timeout ( 15 )) // explode after 15 seconds state = \"explode\" ; } state \"explode\" { Console . print ( \"BOOOM!\" ); parent . destroy (); // destroy the parent object } } object \"Parrot\" is \"entity\" { blabber = spawn ( \"Blabber\" ); bomb = spawn ( \"Time Bomb\" ); state \"main\" { } } Now, here's the output: Hello! Hello! Hello! Hello! Hello! Hello! Hello! BOOOM! In this example, Parrot is an entity and Blabber and Time Bomb are its components. Once the entity is destroyed, its components (its children) are also destroyed automatically.","title":"Introduction"},{"location":"tutorials/components/#design-considerations","text":"In some implementations of ECS, entities are implemented as integers and components consist of raw data only. The game logic is executed by the System layer, which iterates throughout all entities continuously and executes the logic according to the components attached to them. In SurgeScript, components execute their own code and can be attached to entities simply by spawning them as children. Still, you can use the former approach if you wish to do so.","title":"Design considerations"},{"location":"tutorials/components/#composition-over-inheritance","text":"SurgeScript does not explicitly support inheritance, a feature found in other object-oriented languages. The usage of components is encouraged instead. SurgeScript favors composition over inheritance, allowing for greater flexibility when defining in-game objects.","title":"Composition over inheritance"},{"location":"tutorials/conditionals/","text":"Conditionals Introduction Conditionals are if ... then ... statements. If a certain condition evaluates to true , execute a block of code. If not, don't execute it. if ( condition ) { // this will be executed only if // the condition is true } Alternatively, we may include an else statement followed by a block of code that will only be executed if the condition is not true: if ( condition ) { // this will be executed only if // the condition is true } else { // this will be executed only if // the condition is false } Example The following example will print underaged if variable age is less than 18, or adult otherwise: object \"Application\" { age = 23 ; state \"main\" { if ( age < 18 ) { // variable age is less than 18 Console . print ( \"underaged\" ); } else { // variable age is not less than 18 Console . print ( \"adult\" ); } } } Inline conditionals Just like other languages with C-based syntax, the expression condition ? true_value : false_value evaluates to true_value if condition is true and to false_value if condition is false . For example, the script below will print underaged if variable age is less than 18, or adult otherwise: object \"Application\" { age = 23 ; message = age < 18 ? \"underaged\" : \"adult\" ; state \"main\" { Console . print ( message ); } }","title":"Conditionals"},{"location":"tutorials/conditionals/#conditionals","text":"","title":"Conditionals"},{"location":"tutorials/conditionals/#introduction","text":"Conditionals are if ... then ... statements. If a certain condition evaluates to true , execute a block of code. If not, don't execute it. if ( condition ) { // this will be executed only if // the condition is true } Alternatively, we may include an else statement followed by a block of code that will only be executed if the condition is not true: if ( condition ) { // this will be executed only if // the condition is true } else { // this will be executed only if // the condition is false }","title":"Introduction"},{"location":"tutorials/conditionals/#example","text":"The following example will print underaged if variable age is less than 18, or adult otherwise: object \"Application\" { age = 23 ; state \"main\" { if ( age < 18 ) { // variable age is less than 18 Console . print ( \"underaged\" ); } else { // variable age is not less than 18 Console . print ( \"adult\" ); } } }","title":"Example"},{"location":"tutorials/conditionals/#inline-conditionals","text":"Just like other languages with C-based syntax, the expression condition ? true_value : false_value evaluates to true_value if condition is true and to false_value if condition is false . For example, the script below will print underaged if variable age is less than 18, or adult otherwise: object \"Application\" { age = 23 ; message = age < 18 ? \"underaged\" : \"adult\" ; state \"main\" { Console . print ( message ); } }","title":"Inline conditionals"},{"location":"tutorials/expressions/","text":"Expressions SurgeScript supports many kinds of expressions. Expressions may involve strings, numbers or booleans. Let's study each case: Constants Constants are types of expressions. They may be numbers, strings, booleans... You may attribute constant values to variables using the assignment operator ( = ): // strings name = \"Surge\" ; // variable name receives string \"Surge\" message = \"Surge's home\" ; otherMessage = ' Single - quoted strings are also allowed ' ; // numbers weight = 35 ; speed = 42.2 ; // booleans like = true ; crazy = false ; // null next = null ; Arithmetic operators SurgeScript can perform basic arithmetic. The operators are as follows: Operator Meaning + Addition - Subtraction * Multiplication / Division % Remainder The multiplication, division and remainder operators have precedence over the addition and the subtraction operators. Examples: two = 1 + 1 ; ten = 5 * 2 ; eleven = 5 * 2 + 1 ; four = two * two ; fifteen = eleven + four ; three = fifteen / 5 ; positive = + 5 ; negative = - 1 ; zero = 15 - 10 - 5 ; one = 15 - ( 10 + 4 ); twelve = ( 2 + 2 ) * 3 ; prime = -(- 15 + 8 ); seven = 5 + 5 % 3 ; negativeTwo = - 5 % 3 ; Comparison operators Comparison operators compare two operands. Operator Meaning == Equality operator != Inequality operator < Less than <= Less or equal > Greater than >= Greater or equal === Strong equality !== Strong inequality Examples: x = 1 ; y = ( x == 1 ); // y is true z = ( x != 1 ); // z is false w = x > 1 ; // w is false t = x >= 1 ; // t is true Pay attention! Notice that the equality operator, used for comparing expressions for equality, is == . Pay attention! Don't confuse the equality operator ( == ) with the assignment operator ( = ). The expression (x = 1) always evaluates to 1, whereas (x == 1) is true only if x equals 1. Strong equality Unlike their counterparts, strong equality/inequality operators compare not only the content of the operands, but also their type. While \"1\" == 1 evalutes to true , \"1\" === 1 does not. Logical operators Logical operators involve booleans ( true or false values). While the not operator requires only one operand, operators and and or require two. Operator Meaning && and || or ! not The table below summarizes the basic logical expressions: Expression Result a && b true only if both a and b are true a || b true if a is true or b is true !a true if a is false, false if a is true Notice that not has higher precedence than the other two operators. Examples: x = 5 < 2 ; // evaluates to false y = ! x ; // evaluates to true z = 18 < 35 || x ; // evaluates to true w = ( z && x ) || true ; // evaluates to true t = ! x && x ; // evaluates to false Short-circuit evaluation SurgeScript performs short-circuit evaluation in and and or operations. This means that the second operator is not evaluated if the first alone is sufficient to determine the value of the operation. Example: in the expression a || b , expression b is not evaluated if a is evaluated to true . Similarly, in a && b , expression b is not evaluated if a is evaluated to false . Textual expressions You may concatenate strings with the + operator. Example: message = \"Surge\" + \" rocks!\" ; // evaluates to \"Surge rocks!\" Other data types, such as numbers and booleans, may also be implicitly converted to strings when using this feature. Example: group = \"Jackson \" + 5 ; // evaluates to \"Jackson 5\" Assignment operators The attribution operator ( = ) may be used to attribute data to variables. However, there's more to it. The expression variable = \"data\" is itself evaluated to string \"data\" . Likewise, the expression variable = variable + 5 is evaluated to the new value of the variable and may be shortened to variable += 5 . Let's see what kind of assignment expressions we have: Expression Translates to Meaning x = value x = value Assigns value to x x += value x = x + value Adds value to x x -= value x = x - value Subtracts value from x x *= value x = x * value Multiplies x by value x /= value x = x / value Divides x by value x %= value x = x % value Sets x to the remainder of x / value Example: language = \"Surge\" ; language += \"Script\" ; // language now evaluates to \"SurgeScript\" number = 5 ; number += 2 ; // number now evaluates to 7 Increment and decrement Increment and decrement operators should be used only on numeric variables. Expression Meaning x++ Increments x by 1 and returns the old value of x x-- Decrements x by 1 and returns the old value of x ++x Increments x by 1 and returns the new value of x --x Decrements x by 1 and returns the new value of x Example: x = 1 ; // x is 1 y = x ++; // y is 1 z = ++ x ; // z is 3 w = -- x ; // w is 2 t = -- x ; // t is 1 Console . print ( x ); // prints 1 Chained expressions You may chain assignment operations: x = y = z = 1 ; Commas The comma operator takes two operands. It first evaluates the first operand and then discards the result. Next, it evaluates the second operand and then returns this result. The comma is the operator with the lowest precedence. c = ( 1 , 2 ); // Results in c = 2 a = 1 , b = 2 , c = 3 ; // Results in a = 1, b = 2 and c = 3 d = ( c ++, a ); // Results in c = 4, d = 1 e = (++ a , f = 2 , 3 ); // Results in a = 2, e = 3, f = 2 Other expressions this The keyword this represents the object in which it appears. Example: this . destroy (); // destroys this object typeof The expression typeof(expr) (or simply typeof expr ), is evaluated to a string corresponding to the type of expr . The possible types are: number , string , boolean , object or null . Example: t = typeof 5 ; // t will hold the string \"number\" timeout The expression timeout(seconds) is a handy feature of SurgeScript. It is evaluated to true if the object has been on the same state for the specified amount of time or more. It can only be used inside states. Example: object \"Application\" { state \"main\" { if ( timeout ( 2.0 )) { Console . print ( \"2 seconds have passed\" ); state = \"done\" ; } } state \"done\" { } }","title":"Expressions"},{"location":"tutorials/expressions/#expressions","text":"SurgeScript supports many kinds of expressions. Expressions may involve strings, numbers or booleans. Let's study each case:","title":"Expressions"},{"location":"tutorials/expressions/#constants","text":"Constants are types of expressions. They may be numbers, strings, booleans... You may attribute constant values to variables using the assignment operator ( = ): // strings name = \"Surge\" ; // variable name receives string \"Surge\" message = \"Surge's home\" ; otherMessage = ' Single - quoted strings are also allowed ' ; // numbers weight = 35 ; speed = 42.2 ; // booleans like = true ; crazy = false ; // null next = null ;","title":"Constants"},{"location":"tutorials/expressions/#arithmetic-operators","text":"SurgeScript can perform basic arithmetic. The operators are as follows: Operator Meaning + Addition - Subtraction * Multiplication / Division % Remainder The multiplication, division and remainder operators have precedence over the addition and the subtraction operators. Examples: two = 1 + 1 ; ten = 5 * 2 ; eleven = 5 * 2 + 1 ; four = two * two ; fifteen = eleven + four ; three = fifteen / 5 ; positive = + 5 ; negative = - 1 ; zero = 15 - 10 - 5 ; one = 15 - ( 10 + 4 ); twelve = ( 2 + 2 ) * 3 ; prime = -(- 15 + 8 ); seven = 5 + 5 % 3 ; negativeTwo = - 5 % 3 ;","title":"Arithmetic operators"},{"location":"tutorials/expressions/#comparison-operators","text":"Comparison operators compare two operands. Operator Meaning == Equality operator != Inequality operator < Less than <= Less or equal > Greater than >= Greater or equal === Strong equality !== Strong inequality Examples: x = 1 ; y = ( x == 1 ); // y is true z = ( x != 1 ); // z is false w = x > 1 ; // w is false t = x >= 1 ; // t is true Pay attention! Notice that the equality operator, used for comparing expressions for equality, is == . Pay attention! Don't confuse the equality operator ( == ) with the assignment operator ( = ). The expression (x = 1) always evaluates to 1, whereas (x == 1) is true only if x equals 1. Strong equality Unlike their counterparts, strong equality/inequality operators compare not only the content of the operands, but also their type. While \"1\" == 1 evalutes to true , \"1\" === 1 does not.","title":"Comparison operators"},{"location":"tutorials/expressions/#logical-operators","text":"Logical operators involve booleans ( true or false values). While the not operator requires only one operand, operators and and or require two. Operator Meaning && and || or ! not The table below summarizes the basic logical expressions: Expression Result a && b true only if both a and b are true a || b true if a is true or b is true !a true if a is false, false if a is true Notice that not has higher precedence than the other two operators. Examples: x = 5 < 2 ; // evaluates to false y = ! x ; // evaluates to true z = 18 < 35 || x ; // evaluates to true w = ( z && x ) || true ; // evaluates to true t = ! x && x ; // evaluates to false Short-circuit evaluation SurgeScript performs short-circuit evaluation in and and or operations. This means that the second operator is not evaluated if the first alone is sufficient to determine the value of the operation. Example: in the expression a || b , expression b is not evaluated if a is evaluated to true . Similarly, in a && b , expression b is not evaluated if a is evaluated to false .","title":"Logical operators"},{"location":"tutorials/expressions/#textual-expressions","text":"You may concatenate strings with the + operator. Example: message = \"Surge\" + \" rocks!\" ; // evaluates to \"Surge rocks!\" Other data types, such as numbers and booleans, may also be implicitly converted to strings when using this feature. Example: group = \"Jackson \" + 5 ; // evaluates to \"Jackson 5\"","title":"Textual expressions"},{"location":"tutorials/expressions/#assignment-operators","text":"The attribution operator ( = ) may be used to attribute data to variables. However, there's more to it. The expression variable = \"data\" is itself evaluated to string \"data\" . Likewise, the expression variable = variable + 5 is evaluated to the new value of the variable and may be shortened to variable += 5 . Let's see what kind of assignment expressions we have: Expression Translates to Meaning x = value x = value Assigns value to x x += value x = x + value Adds value to x x -= value x = x - value Subtracts value from x x *= value x = x * value Multiplies x by value x /= value x = x / value Divides x by value x %= value x = x % value Sets x to the remainder of x / value Example: language = \"Surge\" ; language += \"Script\" ; // language now evaluates to \"SurgeScript\" number = 5 ; number += 2 ; // number now evaluates to 7","title":"Assignment operators"},{"location":"tutorials/expressions/#increment-and-decrement","text":"Increment and decrement operators should be used only on numeric variables. Expression Meaning x++ Increments x by 1 and returns the old value of x x-- Decrements x by 1 and returns the old value of x ++x Increments x by 1 and returns the new value of x --x Decrements x by 1 and returns the new value of x Example: x = 1 ; // x is 1 y = x ++; // y is 1 z = ++ x ; // z is 3 w = -- x ; // w is 2 t = -- x ; // t is 1 Console . print ( x ); // prints 1","title":"Increment and decrement"},{"location":"tutorials/expressions/#chained-expressions","text":"You may chain assignment operations: x = y = z = 1 ;","title":"Chained expressions"},{"location":"tutorials/expressions/#commas","text":"The comma operator takes two operands. It first evaluates the first operand and then discards the result. Next, it evaluates the second operand and then returns this result. The comma is the operator with the lowest precedence. c = ( 1 , 2 ); // Results in c = 2 a = 1 , b = 2 , c = 3 ; // Results in a = 1, b = 2 and c = 3 d = ( c ++, a ); // Results in c = 4, d = 1 e = (++ a , f = 2 , 3 ); // Results in a = 2, e = 3, f = 2","title":"Commas"},{"location":"tutorials/expressions/#other-expressions","text":"","title":"Other expressions"},{"location":"tutorials/expressions/#this","text":"The keyword this represents the object in which it appears. Example: this . destroy (); // destroys this object","title":"this"},{"location":"tutorials/expressions/#typeof","text":"The expression typeof(expr) (or simply typeof expr ), is evaluated to a string corresponding to the type of expr . The possible types are: number , string , boolean , object or null . Example: t = typeof 5 ; // t will hold the string \"number\"","title":"typeof"},{"location":"tutorials/expressions/#timeout","text":"The expression timeout(seconds) is a handy feature of SurgeScript. It is evaluated to true if the object has been on the same state for the specified amount of time or more. It can only be used inside states. Example: object \"Application\" { state \"main\" { if ( timeout ( 2.0 )) { Console . print ( \"2 seconds have passed\" ); state = \"done\" ; } } state \"done\" { } }","title":"timeout"},{"location":"tutorials/functions/","text":"Functions Introduction Functions are blocks of code that you can reuse throughout your program. They may receive input parameters and they always output something. The syntax is as follows: fun function_name ( param_1 , param_2 , param_3 , ..., param_n ) { // block of code // to be executed } Functions may be associated to objects. Any function associated to an object may be used (called) by the object itself or by other objects. This means that functions are public (they are visible to the outside world). Note: functions must be defined after the states. Return statement Use the return statement to stop executing the function and to return some value to the caller. Example: // This function will return the double of input parameter x fun double ( x ) { return 2 * x ; Console . print ( \"This line will never be executed.\" ); } If no value is specified after the return keyword, the function will be stopped and its return value will be null . Additionally, if no return statement is found, then the return value will also be null . Note : an object state may also contain one or more return statements to stop the execution of its code. However, return values must not be specified in that context, since states do not return values. Simple example In the example below, we have an object called Calculator with two functions: greet() and sum() . greet() takes no input parameters and just greets the user. On the other hand, sum() takes two input parameters, a and b , and returns the sum a + b : object \"Calculator\" { fun greet () { Console . print ( \"Hello! I am a Calculator!\" ); } fun sum ( a , b ) { return a + b ; } } In function sum() , variables a and b hold the input data and are only visible inside the function. Now, let's create a program that uses this Calculator . Remember that the functions defined above can be called by any object, including Application : object \"Application\" { calculator = spawn ( \"Calculator\" ); state \"main\" { // greet the user calculator . greet (); // do some computation result = calculator . sum ( 5 , 7 ); Console . print ( result ); // we're done! Application . exit (); } } The output of the above program is: Hello! I am a Calculator! 12 Notice that the Application does not need to know how the functions of the Calculator are implemented. It just needs to know what they do. This means that you may change the implementation of the Calculator without changing the Application , and the end-result will stay the same. Recursive functions In SurgeScript, a function is said to be recursive when it calls itself within its code. Recursion can be useful in many ways; namely, when you define a problem in terms of itself. In mathematics, the factorial of a non-negative integer number n , denoted as n! , is such an example: n! = { n * (n-1)! if n > 1 { 1 otherwise One interesting example of recursion that arises in computer science is called the binary search algorithm. Given a sorted Array , the binary search finds the position of a target value without having to inspect the whole collection. In the example below, bsearch() is a recursive function: object \"Binary Search\" { // Given an array sorted in ascending order, find() // finds the position of the target value in the array. // It returns its index, or -1 if the target is not found. fun find ( array , value ) { return bsearch ( array , value , 0 , array . length - 1 ); } // Performs a binary search in array[start..end] fun bsearch ( array , value , start , end ) { // get the middle point mid = start + Math . floor (( end - start ) / 2 ); // compare the middle point to the target value if ( start > end ) return - 1 ; // target not found else if ( value == array [ mid ]) return mid ; // found the target value else if ( value < array [ mid ]) return bsearch ( array , value , start , mid - 1 ); else return bsearch ( array , value , mid + 1 , end ); } } Recursive functions must have at least one base case. A base case is a scenario that does not need recursion to solve the problem. In the factorial example, the base case is n <= 1 (the factorial is 1). In the binary search example, the base case is start > end , meaning that the array is empty and the target value cannot be found, or value == array[mid] , meaning that the target value has been found at mid . How to understand recursion A sage once said: \"to understand recursion, you must first understand recursion\". Constructors and destructors In SurgeScript, constructors and destructors are special functions that are called whenever objects are created and destroyed, respectively. It's not mandatory to define them, but it may be useful to do so (you may want to set up things in your constructors, for example). Neither may receive any arguments (to set up objects with parameters, take a look at chaining ). Let's take our Calculator again. In the following example, constructor() is called automatically whenever a Calculator object is created. Likewise, destructor() is called automatically when the object is destroyed. object \"Calculator\" { fun constructor () { Console . print ( \"Creating a Calculator...\" ); } fun destructor () { Console . print ( \"Destroying a Calculator...\" ); } fun greet () { Console . print ( \"Hello! I am a Calculator!\" ); } fun sum ( a , b ) { return a + b ; } } Now, if we run the Application of the previous section without any modification, the output of the program will be: Creating a Calculator... Hello! I am a Calculator! 12 Destroying a Calculator... Note that, for any object, its constructor() runs before its main state.","title":"Functions"},{"location":"tutorials/functions/#functions","text":"","title":"Functions"},{"location":"tutorials/functions/#introduction","text":"Functions are blocks of code that you can reuse throughout your program. They may receive input parameters and they always output something. The syntax is as follows: fun function_name ( param_1 , param_2 , param_3 , ..., param_n ) { // block of code // to be executed } Functions may be associated to objects. Any function associated to an object may be used (called) by the object itself or by other objects. This means that functions are public (they are visible to the outside world). Note: functions must be defined after the states.","title":"Introduction"},{"location":"tutorials/functions/#return-statement","text":"Use the return statement to stop executing the function and to return some value to the caller. Example: // This function will return the double of input parameter x fun double ( x ) { return 2 * x ; Console . print ( \"This line will never be executed.\" ); } If no value is specified after the return keyword, the function will be stopped and its return value will be null . Additionally, if no return statement is found, then the return value will also be null . Note : an object state may also contain one or more return statements to stop the execution of its code. However, return values must not be specified in that context, since states do not return values.","title":"Return statement"},{"location":"tutorials/functions/#simple-example","text":"In the example below, we have an object called Calculator with two functions: greet() and sum() . greet() takes no input parameters and just greets the user. On the other hand, sum() takes two input parameters, a and b , and returns the sum a + b : object \"Calculator\" { fun greet () { Console . print ( \"Hello! I am a Calculator!\" ); } fun sum ( a , b ) { return a + b ; } } In function sum() , variables a and b hold the input data and are only visible inside the function. Now, let's create a program that uses this Calculator . Remember that the functions defined above can be called by any object, including Application : object \"Application\" { calculator = spawn ( \"Calculator\" ); state \"main\" { // greet the user calculator . greet (); // do some computation result = calculator . sum ( 5 , 7 ); Console . print ( result ); // we're done! Application . exit (); } } The output of the above program is: Hello! I am a Calculator! 12 Notice that the Application does not need to know how the functions of the Calculator are implemented. It just needs to know what they do. This means that you may change the implementation of the Calculator without changing the Application , and the end-result will stay the same.","title":"Simple example"},{"location":"tutorials/functions/#recursive-functions","text":"In SurgeScript, a function is said to be recursive when it calls itself within its code. Recursion can be useful in many ways; namely, when you define a problem in terms of itself. In mathematics, the factorial of a non-negative integer number n , denoted as n! , is such an example: n! = { n * (n-1)! if n > 1 { 1 otherwise One interesting example of recursion that arises in computer science is called the binary search algorithm. Given a sorted Array , the binary search finds the position of a target value without having to inspect the whole collection. In the example below, bsearch() is a recursive function: object \"Binary Search\" { // Given an array sorted in ascending order, find() // finds the position of the target value in the array. // It returns its index, or -1 if the target is not found. fun find ( array , value ) { return bsearch ( array , value , 0 , array . length - 1 ); } // Performs a binary search in array[start..end] fun bsearch ( array , value , start , end ) { // get the middle point mid = start + Math . floor (( end - start ) / 2 ); // compare the middle point to the target value if ( start > end ) return - 1 ; // target not found else if ( value == array [ mid ]) return mid ; // found the target value else if ( value < array [ mid ]) return bsearch ( array , value , start , mid - 1 ); else return bsearch ( array , value , mid + 1 , end ); } } Recursive functions must have at least one base case. A base case is a scenario that does not need recursion to solve the problem. In the factorial example, the base case is n <= 1 (the factorial is 1). In the binary search example, the base case is start > end , meaning that the array is empty and the target value cannot be found, or value == array[mid] , meaning that the target value has been found at mid . How to understand recursion A sage once said: \"to understand recursion, you must first understand recursion\".","title":"Recursive functions"},{"location":"tutorials/functions/#constructors-and-destructors","text":"In SurgeScript, constructors and destructors are special functions that are called whenever objects are created and destroyed, respectively. It's not mandatory to define them, but it may be useful to do so (you may want to set up things in your constructors, for example). Neither may receive any arguments (to set up objects with parameters, take a look at chaining ). Let's take our Calculator again. In the following example, constructor() is called automatically whenever a Calculator object is created. Likewise, destructor() is called automatically when the object is destroyed. object \"Calculator\" { fun constructor () { Console . print ( \"Creating a Calculator...\" ); } fun destructor () { Console . print ( \"Destroying a Calculator...\" ); } fun greet () { Console . print ( \"Hello! I am a Calculator!\" ); } fun sum ( a , b ) { return a + b ; } } Now, if we run the Application of the previous section without any modification, the output of the program will be: Creating a Calculator... Hello! I am a Calculator! 12 Destroying a Calculator... Note that, for any object, its constructor() runs before its main state.","title":"Constructors and destructors"},{"location":"tutorials/hello/","text":"Hello, World! SurgeScript creates automatically an object called Application . That object is defined by the user. Let's see how we can use that to make a simple program: object \"Application\" { state \"main\" { Console . print ( \"Hello, world!\" ); Application . exit (); } } In SurgeScript, each object defines a state machine (more on that later). The initial state is called main . In the code just presented, we display a Hello, world! message and then exit the app. Now let's test your scripts .","title":"Hello, World!"},{"location":"tutorials/hello/#hello-world","text":"SurgeScript creates automatically an object called Application . That object is defined by the user. Let's see how we can use that to make a simple program: object \"Application\" { state \"main\" { Console . print ( \"Hello, world!\" ); Application . exit (); } } In SurgeScript, each object defines a state machine (more on that later). The initial state is called main . In the code just presented, we display a Hello, world! message and then exit the app. Now let's test your scripts .","title":"Hello, World!"},{"location":"tutorials/loops/","text":"Loops While loops In a while loop, you execute a certain block of code while a condition is true. The syntax is as follows: while ( condition ) { // block of code // to be executed } The example below counts from 1 to 10: i = 1 ; while ( i <= 10 ) { Console . print ( i ); i = i + 1 ; } The following example prints nothing. The while loop is skipped because the condition is initially false: i = 20 ; while ( i <= 10 ) { // this condition is false Console . print ( i ); i = i + 1 ; } Do-while loops Do-while loops are similar to while loops, except that the block of code is executed at least once, unconditionally. It is repeated while a condition is true. Syntax: do { // block of code // to be executed } while ( condition ); The example below counts from 1 to 10: i = 1 ; do { Console . print ( i ); i = i + 1 ; } while ( i <= 10 ); The following example prints the number 20. Since the condition is false, the block of code is executed only once: i = 20 ; do { Console . print ( i ); i = i + 1 ; } while ( i <= 10 ); // this condition is false Note: do-while loops are available since SurgeScript 0.6.0. For loops A for loop is a more controlled repetition structure compared to a while loop. For loops support an initialization command, a condition and an increment command. The syntax is as follows: for ( initialization ; condition ; increment ) { // block of code // to be executed } The for loop above is equivalent to: initialization ; while ( condition ) { // block of code // to be executed increment ; } The example below counts from 1 to 10: for ( i = 1 ; i <= 10 ; i ++) { Console . print ( i ); } Foreach Foreach loops are used to iterate throughout iterable collections (such as Arrays and Dictionaries ). Basically: for each element x in the iterable collection, do something with x . The syntax is as follows: foreach ( element in collection ) { // block of code // to be executed } The example below counts from 1 to 10: collection = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]; foreach ( x in collection ) { Console . print ( x ); } The example below iterates over a Dictionary : dictionary = { \"a\" : 1 , \"b\" : 2 , \"c\" : 3 }; foreach ( entry in dictionary ) { Console . print ( entry . key ); Console . print ( entry . value ); } Implementing your own iterable collections The foreach loop can be used with any iterable collections, not only Arrays and Dictionaries . You may even implement your own!","title":"Loops"},{"location":"tutorials/loops/#loops","text":"","title":"Loops"},{"location":"tutorials/loops/#while-loops","text":"In a while loop, you execute a certain block of code while a condition is true. The syntax is as follows: while ( condition ) { // block of code // to be executed } The example below counts from 1 to 10: i = 1 ; while ( i <= 10 ) { Console . print ( i ); i = i + 1 ; } The following example prints nothing. The while loop is skipped because the condition is initially false: i = 20 ; while ( i <= 10 ) { // this condition is false Console . print ( i ); i = i + 1 ; }","title":"While loops"},{"location":"tutorials/loops/#do-while-loops","text":"Do-while loops are similar to while loops, except that the block of code is executed at least once, unconditionally. It is repeated while a condition is true. Syntax: do { // block of code // to be executed } while ( condition ); The example below counts from 1 to 10: i = 1 ; do { Console . print ( i ); i = i + 1 ; } while ( i <= 10 ); The following example prints the number 20. Since the condition is false, the block of code is executed only once: i = 20 ; do { Console . print ( i ); i = i + 1 ; } while ( i <= 10 ); // this condition is false Note: do-while loops are available since SurgeScript 0.6.0.","title":"Do-while loops"},{"location":"tutorials/loops/#for-loops","text":"A for loop is a more controlled repetition structure compared to a while loop. For loops support an initialization command, a condition and an increment command. The syntax is as follows: for ( initialization ; condition ; increment ) { // block of code // to be executed } The for loop above is equivalent to: initialization ; while ( condition ) { // block of code // to be executed increment ; } The example below counts from 1 to 10: for ( i = 1 ; i <= 10 ; i ++) { Console . print ( i ); }","title":"For loops"},{"location":"tutorials/loops/#foreach","text":"Foreach loops are used to iterate throughout iterable collections (such as Arrays and Dictionaries ). Basically: for each element x in the iterable collection, do something with x . The syntax is as follows: foreach ( element in collection ) { // block of code // to be executed } The example below counts from 1 to 10: collection = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]; foreach ( x in collection ) { Console . print ( x ); } The example below iterates over a Dictionary : dictionary = { \"a\" : 1 , \"b\" : 2 , \"c\" : 3 }; foreach ( entry in dictionary ) { Console . print ( entry . key ); Console . print ( entry . value ); } Implementing your own iterable collections The foreach loop can be used with any iterable collections, not only Arrays and Dictionaries . You may even implement your own!","title":"Foreach"},{"location":"tutorials/object_tree/","text":"Object tree Introduction In SurgeScript, objects have a hierarchical relationship. Suppose that object P spawns (or instantiates ) object C. We say that object P is the parent of C. Similarly, object C is a child of P. An object may spawn many children. However, all objects have only one parent. This relationship between objects forms a hierarchy (a tree). The Figure below shows an example: In this example, Level is the parent of GameItem1 and GameItem2. Components A and B are children of GameItem1, but not of GameItem2. Level has two children and GameItem2 has zero. Finally, GameItem1, GameItem2, Component A and Component B are all descendants of Level. In SurgeScript, the root of the hierarchy is a predefined object called System . Its parent is itself. All other objects are descendants of System . Spawning objects You can use spawn() to instantiate an object. Example: object \"Parent\" { child = spawn ( \"Child\" ); state \"main\" { } } object \"Child\" { state \"main\" { } } Function spawn() may be invoked on objects other than the caller. In this case, the caller won't be the parent of the newly created object: object \"Parent\" { child = spawn ( \"Child\" ); grandChild = child . spawn ( \"Child\" ); state \"main\" { } } Automatic Garbage Collection When you spawn an object, make sure you store a reference to it somewhere. If an object cannot be reached from the root (no reachable object has any references to it), it will be automatically destroyed by SurgeScript's built-in garbage collector. Destroying objects Objects can be destroyed manually by calling destroy() . Whenever an object is destroyed, its children are destroyed as well. object \"Foo\" { state \"main\" { Console . print ( \"This object does nothing.\" ); destroy (); } } Traversing the hierarchy Relevant data about the object hierarchy can be obtained using the following properties and functions (find out more about them at the Object reference ): Function / property Description obj.parent The parent object obj.child(name) Gets a child object named name obj.findObject(name) Finds a descendant named name obj.__childCount Number of immediate children Example: object \"Parent\" { child = spawn ( \"Child\" ); otherChild = spawn ( \"Child\" ); state \"main\" { Console . print ( \"This object has \" + this . __childCount + \" children.\" ); destroy (); } } The output is as follows: This object has 2 children.","title":"Object tree"},{"location":"tutorials/object_tree/#object-tree","text":"","title":"Object tree"},{"location":"tutorials/object_tree/#introduction","text":"In SurgeScript, objects have a hierarchical relationship. Suppose that object P spawns (or instantiates ) object C. We say that object P is the parent of C. Similarly, object C is a child of P. An object may spawn many children. However, all objects have only one parent. This relationship between objects forms a hierarchy (a tree). The Figure below shows an example: In this example, Level is the parent of GameItem1 and GameItem2. Components A and B are children of GameItem1, but not of GameItem2. Level has two children and GameItem2 has zero. Finally, GameItem1, GameItem2, Component A and Component B are all descendants of Level. In SurgeScript, the root of the hierarchy is a predefined object called System . Its parent is itself. All other objects are descendants of System .","title":"Introduction"},{"location":"tutorials/object_tree/#spawning-objects","text":"You can use spawn() to instantiate an object. Example: object \"Parent\" { child = spawn ( \"Child\" ); state \"main\" { } } object \"Child\" { state \"main\" { } } Function spawn() may be invoked on objects other than the caller. In this case, the caller won't be the parent of the newly created object: object \"Parent\" { child = spawn ( \"Child\" ); grandChild = child . spawn ( \"Child\" ); state \"main\" { } } Automatic Garbage Collection When you spawn an object, make sure you store a reference to it somewhere. If an object cannot be reached from the root (no reachable object has any references to it), it will be automatically destroyed by SurgeScript's built-in garbage collector.","title":"Spawning objects"},{"location":"tutorials/object_tree/#destroying-objects","text":"Objects can be destroyed manually by calling destroy() . Whenever an object is destroyed, its children are destroyed as well. object \"Foo\" { state \"main\" { Console . print ( \"This object does nothing.\" ); destroy (); } }","title":"Destroying objects"},{"location":"tutorials/object_tree/#traversing-the-hierarchy","text":"Relevant data about the object hierarchy can be obtained using the following properties and functions (find out more about them at the Object reference ): Function / property Description obj.parent The parent object obj.child(name) Gets a child object named name obj.findObject(name) Finds a descendant named name obj.__childCount Number of immediate children Example: object \"Parent\" { child = spawn ( \"Child\" ); otherChild = spawn ( \"Child\" ); state \"main\" { Console . print ( \"This object has \" + this . __childCount + \" children.\" ); destroy (); } } The output is as follows: This object has 2 children.","title":"Traversing the hierarchy"},{"location":"tutorials/objects/","text":"Introduction to objects Introduction In SurgeScript, objects are units of code and data. Each object defines a finite state machine, a mathematical construct used to describe the behavior of in-game objects. Did you know? Games implement what is called a game loop. In SurgeScript, the game loop is defined implicitly via state machines. State machines are one of the key features of SurgeScript. State machines A finite state machine is a mathematical abstraction composed of a finite number of states and by transitions between these states. Only one state can be active at any given time (we'll call it the active state ). There must be one initial state (i.e., the first one to be active). A transition is a change of the active state that is triggered when a certain condition is met. As a concrete example, suppose that you want to create a door in your game. You, the developer, may open or close the door at will. But what is a door? We have just given informal description of the problem. However, we need to transform it in something more rigorous. Example: A door is an object with two states (see the Figure below): Opened (initial state) Closed From the Opened state, only one transition is possible: Close. Once the Close transition is called, the door will go to the Closed state. Conversely, from the Closed state, only one transition is available: Open. When the Open transition is executed, the door will return to the Opened state. Objects in SurgeScript In SurgeScript, each object has a name. Objects may have any number of states you'd like. The initial state is always called main . The syntax is as follows: object \"name of the object\" { state \"state name\" { // code goes here } } The following code shows an example of a door that opens and closes (it keep changing states) every 2 seconds: object \"Cosmic Door\" { state \"main\" { // the object starts at the main state state = \"opened\" ; // go to the opened state } state \"opened\" { if ( timeout ( 2 )) // if we have been on the opened state for 2+ seconds state = \"closed\" ; // go to the closed state } state \"closed\" { if ( timeout ( 2 )) state = \"opened\" ; } } Notice how the code just shown defines states and transitions between these states. Each state contains its own code. Note: once a state is active, its code will be repeated at every frame of the application until the state changes or until the object is destroyed.","title":"Introduction to objects"},{"location":"tutorials/objects/#introduction-to-objects","text":"","title":"Introduction to objects"},{"location":"tutorials/objects/#introduction","text":"In SurgeScript, objects are units of code and data. Each object defines a finite state machine, a mathematical construct used to describe the behavior of in-game objects. Did you know? Games implement what is called a game loop. In SurgeScript, the game loop is defined implicitly via state machines. State machines are one of the key features of SurgeScript.","title":"Introduction"},{"location":"tutorials/objects/#state-machines","text":"A finite state machine is a mathematical abstraction composed of a finite number of states and by transitions between these states. Only one state can be active at any given time (we'll call it the active state ). There must be one initial state (i.e., the first one to be active). A transition is a change of the active state that is triggered when a certain condition is met. As a concrete example, suppose that you want to create a door in your game. You, the developer, may open or close the door at will. But what is a door? We have just given informal description of the problem. However, we need to transform it in something more rigorous. Example: A door is an object with two states (see the Figure below): Opened (initial state) Closed From the Opened state, only one transition is possible: Close. Once the Close transition is called, the door will go to the Closed state. Conversely, from the Closed state, only one transition is available: Open. When the Open transition is executed, the door will return to the Opened state.","title":"State machines"},{"location":"tutorials/objects/#objects-in-surgescript","text":"In SurgeScript, each object has a name. Objects may have any number of states you'd like. The initial state is always called main . The syntax is as follows: object \"name of the object\" { state \"state name\" { // code goes here } } The following code shows an example of a door that opens and closes (it keep changing states) every 2 seconds: object \"Cosmic Door\" { state \"main\" { // the object starts at the main state state = \"opened\" ; // go to the opened state } state \"opened\" { if ( timeout ( 2 )) // if we have been on the opened state for 2+ seconds state = \"closed\" ; // go to the closed state } state \"closed\" { if ( timeout ( 2 )) state = \"opened\" ; } } Notice how the code just shown defines states and transitions between these states. Each state contains its own code. Note: once a state is active, its code will be repeated at every frame of the application until the state changes or until the object is destroyed.","title":"Objects in SurgeScript"},{"location":"tutorials/packages/","text":"Packages Introduction Packages are objects that allow you to extend the functionalities of the language. Once declared, they can be imported anywhere in the code. They can also be easily shared with others, so everyone benefits. Available since: SurgeScript 0.5.2 Basic example Suppose you want to extend the language by adding new routines related to string manipulation. These routines will be used frequently throughout your project, and you'd like easy access to them. This makes it perfect for implementing them as a package. We'll define an object called StringUtils with a reverse() function that reverses a string. We make the object a package by annotating it with @Package . Take a look at the example below: // File: stringutils.ss @Package object \"StringUtils\" { fun reverse ( str ) { buf = \"\" ; for ( i = str . length - 1 ; i >= 0 ; i --) buf += str [ i ]; return buf ; } } When you annotate an object definition with @Package , SurgeScript will spawn an instance of such an object before spawning the Application . Additionally, the package object may be imported anywhere with the using keyword: // File: app.ss using StringUtils ; object \"Application\" { state \"main\" { str = StringUtils . reverse ( \"alucard\" ); Console . print ( str ); // will print \"dracula\" exit (); } } Note: it's recommended not to include any special characters in the name of your packages. Note: before SurgeScript 0.5.4, you would annotate the object with @Plugin instead. In the example above, Application and StringUtils are located in two separate files. If you want to test them using the SurgeScript command line utility, pass both files as parameters: surgescript package.ss app.ss Spawning order Although packages are spawned before the Application object, for the time being they are spawned in no particular order. You may not access a package from within the constructor of another package, as of now there is no dependency resolver implemented. Use the main state. Package example Packages may aggregate many code units with different functionalities. This lets you separate your code in coherent, logical units and also helps you to distribute it. Suppose that user Parrot , the owner of ParrotSoft , created SurgeScript utilities related to string manipulation, matrix math and complex numbers. He decided to share his code as a single package called ParrotSoft . Since he implemented getters for each of his utilities, his package provides easy access to all of them. Furthermore, he annotated his package with @Package (but not the individual utilities), so his package can be accessed anywhere. // File: parrotsoft.ss @Package object \"ParrotSoft\" { public readonly Matrices = spawn ( \"Parrot Matrices\" ); public readonly Complex = spawn ( \"Parrot Complex\" ); public readonly StringUtils = spawn ( \"Parrot StringUtils\" ); } A user of the ParrotSoft package may import Parrot 's utilities simply by importing the package. Individual utilities may also be imported. The code below shows an example: using ParrotSoft.Matrices.Matrix2 ; using ParrotSoft.Complex ; using ParrotSoft ; object \"Application\" { state \"main\" { identity = Matrix2 ([[ 1 , 0 ], [ 0 , 1 ]]); // 2x2 matrix z = Complex ( 2 , 3 ); // 2 + 3i neon = ParrotSoft . StringUtils . reverse ( \"noen\" ); exit (); } } In the example above, writing Complex is equivalent to writing ParrotSoft.Complex , since we imported this utility with using ParrotSoft.Complex . Notice that ParrotSoft implements a getter for Complex . Additionally, ParrotSoft has been annotated with @Package , but Complex has not . This means that the statement using Complex will not yield the expected result. Since Complex is a part of ParrotSoft , it can only be accessed from it. Finally, since we haven't imported StringUtils explicitly, we type ParrotSoft.StringUtils to access it. Pay attention! Combine related packages into one. Don't pollute the global namespace!","title":"Packages"},{"location":"tutorials/packages/#packages","text":"","title":"Packages"},{"location":"tutorials/packages/#introduction","text":"Packages are objects that allow you to extend the functionalities of the language. Once declared, they can be imported anywhere in the code. They can also be easily shared with others, so everyone benefits. Available since: SurgeScript 0.5.2","title":"Introduction"},{"location":"tutorials/packages/#basic-example","text":"Suppose you want to extend the language by adding new routines related to string manipulation. These routines will be used frequently throughout your project, and you'd like easy access to them. This makes it perfect for implementing them as a package. We'll define an object called StringUtils with a reverse() function that reverses a string. We make the object a package by annotating it with @Package . Take a look at the example below: // File: stringutils.ss @Package object \"StringUtils\" { fun reverse ( str ) { buf = \"\" ; for ( i = str . length - 1 ; i >= 0 ; i --) buf += str [ i ]; return buf ; } } When you annotate an object definition with @Package , SurgeScript will spawn an instance of such an object before spawning the Application . Additionally, the package object may be imported anywhere with the using keyword: // File: app.ss using StringUtils ; object \"Application\" { state \"main\" { str = StringUtils . reverse ( \"alucard\" ); Console . print ( str ); // will print \"dracula\" exit (); } } Note: it's recommended not to include any special characters in the name of your packages. Note: before SurgeScript 0.5.4, you would annotate the object with @Plugin instead. In the example above, Application and StringUtils are located in two separate files. If you want to test them using the SurgeScript command line utility, pass both files as parameters: surgescript package.ss app.ss Spawning order Although packages are spawned before the Application object, for the time being they are spawned in no particular order. You may not access a package from within the constructor of another package, as of now there is no dependency resolver implemented. Use the main state.","title":"Basic example"},{"location":"tutorials/packages/#package-example","text":"Packages may aggregate many code units with different functionalities. This lets you separate your code in coherent, logical units and also helps you to distribute it. Suppose that user Parrot , the owner of ParrotSoft , created SurgeScript utilities related to string manipulation, matrix math and complex numbers. He decided to share his code as a single package called ParrotSoft . Since he implemented getters for each of his utilities, his package provides easy access to all of them. Furthermore, he annotated his package with @Package (but not the individual utilities), so his package can be accessed anywhere. // File: parrotsoft.ss @Package object \"ParrotSoft\" { public readonly Matrices = spawn ( \"Parrot Matrices\" ); public readonly Complex = spawn ( \"Parrot Complex\" ); public readonly StringUtils = spawn ( \"Parrot StringUtils\" ); } A user of the ParrotSoft package may import Parrot 's utilities simply by importing the package. Individual utilities may also be imported. The code below shows an example: using ParrotSoft.Matrices.Matrix2 ; using ParrotSoft.Complex ; using ParrotSoft ; object \"Application\" { state \"main\" { identity = Matrix2 ([[ 1 , 0 ], [ 0 , 1 ]]); // 2x2 matrix z = Complex ( 2 , 3 ); // 2 + 3i neon = ParrotSoft . StringUtils . reverse ( \"noen\" ); exit (); } } In the example above, writing Complex is equivalent to writing ParrotSoft.Complex , since we imported this utility with using ParrotSoft.Complex . Notice that ParrotSoft implements a getter for Complex . Additionally, ParrotSoft has been annotated with @Package , but Complex has not . This means that the statement using Complex will not yield the expected result. Since Complex is a part of ParrotSoft , it can only be accessed from it. Finally, since we haven't imported StringUtils explicitly, we type ParrotSoft.StringUtils to access it. Pay attention! Combine related packages into one. Don't pollute the global namespace!","title":"Package example"},{"location":"tutorials/properties/","text":"Properties Introduction In SurgeScript, object-level variables are private. This means that these variables can only be accessed from the objects that defined them. However, SurgeScript features a syntactic sugar that allows objects to read and/or modify other objects' data in a way that looks like dealing with regular (public) variables. We'll call these \"variables\" properties . Defining properties Suppose you have an object called Animal with an object-level variable called sound and a function named speak() : object \"Animal\" { sound = \"meow!\" ; fun speak () { Console . print ( sound ); } } This object can only speak meow! Let's see: object \"Application\" { animal = spawn ( \"Animal\" ); state \"main\" { animal . speak (); } } Run this script and you'll see: meow! meow! meow! meow! ... What if an external object could modify the sound of the animal? Trying to access animal.sound externally will trigger an error, unless you add the public specifier to your variable: object \"Animal\" { public sound = \"meow!\" ; fun speak () { Console . print ( sound ); } } Now, external objects may access (read and write) the sound variable (or property ): object \"Application\" { animal = spawn ( \"Animal\" ); state \"main\" { animal . sound = \"woof!\" ; animal . speak (); } } Since SurgeScript 0.5.3, you may add the readonly modifier after the public specifier. Doing so disallows the modification of the property by external objects: object \"Animal\" { public readonly sound = \"meow!\" ; fun speak () { Console . print ( sound ); } } object \"Application\" { animal = spawn ( \"Animal\" ); state \"main\" { //animal.sound = \"woof!\"; // will trigger an error //Console.print(animal.sound); // this is allowed animal . speak (); } } Using getters and setters In reality, however, there are no public variables in SurgeScript. Behind the scenes, the language defines special functions called getters and setters that will perform the read/write logic for you. Rather than using public , you may want to define the getters and the setters yourself: object \"Animal\" { sound = \"meow!\" ; fun speak () { Console . print ( sound ); } fun set_sound ( value ) { sound = value ; } fun get_sound () { return sound ; } } This code is semantically the same as setting sound to be public ; this is just a bit longer. An advantage of defining getters and setters by yourself is that you control how the data passes through the objects. You may want to validate the data before changing the internal variables of the objects. Example: // lives must not be a negative number fun set_lives ( value ) { if ( value >= 0 ) lives = value ; else lives = 0 ; }","title":"Properties"},{"location":"tutorials/properties/#properties","text":"","title":"Properties"},{"location":"tutorials/properties/#introduction","text":"In SurgeScript, object-level variables are private. This means that these variables can only be accessed from the objects that defined them. However, SurgeScript features a syntactic sugar that allows objects to read and/or modify other objects' data in a way that looks like dealing with regular (public) variables. We'll call these \"variables\" properties .","title":"Introduction"},{"location":"tutorials/properties/#defining-properties","text":"Suppose you have an object called Animal with an object-level variable called sound and a function named speak() : object \"Animal\" { sound = \"meow!\" ; fun speak () { Console . print ( sound ); } } This object can only speak meow! Let's see: object \"Application\" { animal = spawn ( \"Animal\" ); state \"main\" { animal . speak (); } } Run this script and you'll see: meow! meow! meow! meow! ... What if an external object could modify the sound of the animal? Trying to access animal.sound externally will trigger an error, unless you add the public specifier to your variable: object \"Animal\" { public sound = \"meow!\" ; fun speak () { Console . print ( sound ); } } Now, external objects may access (read and write) the sound variable (or property ): object \"Application\" { animal = spawn ( \"Animal\" ); state \"main\" { animal . sound = \"woof!\" ; animal . speak (); } } Since SurgeScript 0.5.3, you may add the readonly modifier after the public specifier. Doing so disallows the modification of the property by external objects: object \"Animal\" { public readonly sound = \"meow!\" ; fun speak () { Console . print ( sound ); } } object \"Application\" { animal = spawn ( \"Animal\" ); state \"main\" { //animal.sound = \"woof!\"; // will trigger an error //Console.print(animal.sound); // this is allowed animal . speak (); } }","title":"Defining properties"},{"location":"tutorials/properties/#using-getters-and-setters","text":"In reality, however, there are no public variables in SurgeScript. Behind the scenes, the language defines special functions called getters and setters that will perform the read/write logic for you. Rather than using public , you may want to define the getters and the setters yourself: object \"Animal\" { sound = \"meow!\" ; fun speak () { Console . print ( sound ); } fun set_sound ( value ) { sound = value ; } fun get_sound () { return sound ; } } This code is semantically the same as setting sound to be public ; this is just a bit longer. An advantage of defining getters and setters by yourself is that you control how the data passes through the objects. You may want to validate the data before changing the internal variables of the objects. Example: // lives must not be a negative number fun set_lives ( value ) { if ( value >= 0 ) lives = value ; else lives = 0 ; }","title":"Using getters and setters"},{"location":"tutorials/tags/","text":"Tags You may tag objects with as many tags as you want. Tags are a way of attributing categories to objects. Syntax Tags should be placed right after the object name. Example: object \"Horse\" is \"animal\" , \"vehicle\" { state \"main\" { } } object \"Cat\" is \"animal\" { state \"main\" { } } object \"Car\" is \"vehicle\" { state \"main\" { } } Using tags You may check if an object has a particular tag with the hasTag() function (see the Object reference for more details): object \"Application\" { horse = spawn ( \"Horse\" ); cat = spawn ( \"Cat\" ); car = spawn ( \"Car\" ); state \"main\" { // Horse is both an animal and a vehicle Console . print ( horse . hasTag ( \"animal\" )); // true Console . print ( horse . hasTag ( \"vehicle\" )); // true // Cat is an animal, but not a vehicle Console . print ( cat . hasTag ( \"animal\" )); // true Console . print ( cat . hasTag ( \"vehicle\" )); // false // Car is a vehicle, but not an animal Console . print ( car . hasTag ( \"animal\" )); // false Console . print ( car . hasTag ( \"vehicle\" )); // true } }","title":"Tags"},{"location":"tutorials/tags/#tags","text":"You may tag objects with as many tags as you want. Tags are a way of attributing categories to objects.","title":"Tags"},{"location":"tutorials/tags/#syntax","text":"Tags should be placed right after the object name. Example: object \"Horse\" is \"animal\" , \"vehicle\" { state \"main\" { } } object \"Cat\" is \"animal\" { state \"main\" { } } object \"Car\" is \"vehicle\" { state \"main\" { } }","title":"Syntax"},{"location":"tutorials/tags/#using-tags","text":"You may check if an object has a particular tag with the hasTag() function (see the Object reference for more details): object \"Application\" { horse = spawn ( \"Horse\" ); cat = spawn ( \"Cat\" ); car = spawn ( \"Car\" ); state \"main\" { // Horse is both an animal and a vehicle Console . print ( horse . hasTag ( \"animal\" )); // true Console . print ( horse . hasTag ( \"vehicle\" )); // true // Cat is an animal, but not a vehicle Console . print ( cat . hasTag ( \"animal\" )); // true Console . print ( cat . hasTag ( \"vehicle\" )); // false // Car is a vehicle, but not an animal Console . print ( car . hasTag ( \"animal\" )); // false Console . print ( car . hasTag ( \"vehicle\" )); // true } }","title":"Using tags"},{"location":"tutorials/testing/","text":"Testing your scripts There are two main ways to test your scripts: using the Open Surge game engine; using the SurgeScript standalone runtime (i.e., the version without a game engine). Using Open Surge To test a script in Open Surge, place it on the scripts/ folder and start the engine. Your test script must include an object called Application . Make sure to remove the script after you're done with the testing. As an example, save the following script to scripts/hello.ss and start the engine: // hello.ss: test script // Please remove this file after you're done object \"Application\" { state \"main\" { Console . print ( \"Hello, world!\" ); state = \"done\" ; } state \"done\" { } } You should see the Hello, world! message as a result. Linux users: when using a system-wide installation, you may place your scripts on ~/.local/share/opensurge/scripts/ (i.e., $XDG_DATA_HOME/opensurge/scripts/ ). Ready to proceed? Let's go to Introduction to objects ! Using the standalone version If you've downloaded the standalone version of the language: First of all, save the following script to a file named hello.ss . For testing purposes, you may place the file on the same directory as the surgescript executable. // hello.ss: test script object \"Application\" { state \"main\" { Console . print ( \"Hello, world!\" ); Application . exit (); } } Then, open up a Terminal and type: cd /path/to/surgescript ./surgescript hello.ss If you're using Microsoft Windows, open up a Command Prompt and type: cd C:\\path\\to\\surgescript surgescript.exe hello.ss You should see the output of the script as a result: Hello, world! To begin our learning adventure, let's go to Introduction to objects .","title":"Testing your scripts"},{"location":"tutorials/testing/#testing-your-scripts","text":"There are two main ways to test your scripts: using the Open Surge game engine; using the SurgeScript standalone runtime (i.e., the version without a game engine).","title":"Testing your scripts"},{"location":"tutorials/testing/#using-open-surge","text":"To test a script in Open Surge, place it on the scripts/ folder and start the engine. Your test script must include an object called Application . Make sure to remove the script after you're done with the testing. As an example, save the following script to scripts/hello.ss and start the engine: // hello.ss: test script // Please remove this file after you're done object \"Application\" { state \"main\" { Console . print ( \"Hello, world!\" ); state = \"done\" ; } state \"done\" { } } You should see the Hello, world! message as a result. Linux users: when using a system-wide installation, you may place your scripts on ~/.local/share/opensurge/scripts/ (i.e., $XDG_DATA_HOME/opensurge/scripts/ ). Ready to proceed? Let's go to Introduction to objects !","title":"Using Open Surge"},{"location":"tutorials/testing/#using-the-standalone-version","text":"If you've downloaded the standalone version of the language: First of all, save the following script to a file named hello.ss . For testing purposes, you may place the file on the same directory as the surgescript executable. // hello.ss: test script object \"Application\" { state \"main\" { Console . print ( \"Hello, world!\" ); Application . exit (); } } Then, open up a Terminal and type: cd /path/to/surgescript ./surgescript hello.ss If you're using Microsoft Windows, open up a Command Prompt and type: cd C:\\path\\to\\surgescript surgescript.exe hello.ss You should see the output of the script as a result: Hello, world! To begin our learning adventure, let's go to Introduction to objects .","title":"Using the standalone version"},{"location":"tutorials/variables/","text":"Variables Introduction Variables are used to store data. SurgeScript features five basic types: number, string, boolean, null and object. Variables can also point to more complex data structures (such as arrays and dictionaries), but these are always objects. Types Basic types Type Description Examples Number A floating-point number 1 , 2 , -3 , 3.14159 String Some text \"Hello, world!\" , 'single-quoted' Boolean True or false true , false Object Reference to an object Application , this , [ ] Null An empty value null As an example, the script below features an object with 3 variables that may be accessed throughout the whole object: object \"Application\" { name = \"Surge the Rabbit\" ; age = 23 ; underage = false ; state \"main\" { Console . print ( name ); // Surge the Rabbit Console . print ( age ); // 23 } } Abstract types Arrays Arrays are collections of values that you may access using a zero-based index. Example: object \"Application\" { // The 'characters' array holds 3 strings characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; state \"main\" { // who are the characters? Console . print ( \"The characters are:\" ); Console . print ( characters [ 0 ]); // will print Surge Console . print ( characters [ 1 ]); // will print Neon Console . print ( characters [ 2 ]); // will print Charge // how many characters? Console . print ( \"Number of characters:\" ); Console . print ( characters . length ); // will print 3 } } Arrays have many interesting properties and operations that you can see in the Language Reference . Dictionaries Dictionaries are collections of key-value pairs. In some programming languages, these are known as associative arrays or hash tables. Here's the syntax: object \"Application\" { // A dictionary that stores the weight (kg) of each character weight = { \"Surge\" : 35 , \"Neon\" : 30 , \"Charge\" : 37.5 , \"Gimacian\" : 70 }; // print the weights state \"main\" { Console . print ( \"Surge weighs \" + weight [ \"Surge\" ] + \" kg.\" ); Console . print ( \"Neon weighs \" + weight [ \"Neon\" ] + \" kg.\" ); Console . print ( \"Charge weighs \" + weight [ \"Charge\" ] + \" kg.\" ); Console . print ( \"Gimacian weighs \" + weight [ \"Gimacian\" ] + \" kg.\" ); } } Dictionaries have many interesting properties and operations that you can see in the Language Reference . Caution! Whenever you define an array or a dictionary, you spawn a new object. You are advised to NOT define arrays or dictionaries within states, because the code within the states run continuously. New objects will be created at every frame, not just once. object \"Application\" { // arr will be instantiated once the object is created arr = [ 1 , 2 , 3 ]; // RIGHT! state \"main\" { // err is instantiated at every frame of the application, // thus memory is wasted with duplicate objects err = [ \"don't\" , \"do\" , \"this\" ]; // AVOID! } } Casting You can use type-casting to change the type of values from number to string, from string to number, from boolean to string and so on. Casting values is as simple as calling Number(value) , String(value) or Boolean(value) . Example: // Convert string to number str = \"2\" ; val = Number ( str ); // val is 2 // Convert number to string val = 123 ; str = String ( val ); // str is \"123\" When converting an object to a string, SurgeScript will implicitly call object.toString() . Scoping Variables that are defined before any state or function are object-level variables. They can be accessed throughout the whole object. On the other hand, variables used exclusively inside states or functions are local variables . This means that their accessibility and lifespan is restricted to their own locus of code. object \"Scope Test\" { name = \"Surge the Rabbit\" ; // object-level variable state \"main\" { weight = 35 ; // local variable state = \"print-data\" ; // change the state } state \"print-data\" { Console . print ( name ); // Surge the Rabbit Console . print ( weight ); // ERROR: weight is not defined } } Furthermore, object-level variables may only be accessed within the object. Other objects may not read or write the variables directly (in other words, variables are private to the objects). You need to define functions or getters and setters to accomplish that.","title":"Variables"},{"location":"tutorials/variables/#variables","text":"","title":"Variables"},{"location":"tutorials/variables/#introduction","text":"Variables are used to store data. SurgeScript features five basic types: number, string, boolean, null and object. Variables can also point to more complex data structures (such as arrays and dictionaries), but these are always objects.","title":"Introduction"},{"location":"tutorials/variables/#types","text":"","title":"Types"},{"location":"tutorials/variables/#basic-types","text":"Type Description Examples Number A floating-point number 1 , 2 , -3 , 3.14159 String Some text \"Hello, world!\" , 'single-quoted' Boolean True or false true , false Object Reference to an object Application , this , [ ] Null An empty value null As an example, the script below features an object with 3 variables that may be accessed throughout the whole object: object \"Application\" { name = \"Surge the Rabbit\" ; age = 23 ; underage = false ; state \"main\" { Console . print ( name ); // Surge the Rabbit Console . print ( age ); // 23 } }","title":"Basic types"},{"location":"tutorials/variables/#abstract-types","text":"","title":"Abstract types"},{"location":"tutorials/variables/#arrays","text":"Arrays are collections of values that you may access using a zero-based index. Example: object \"Application\" { // The 'characters' array holds 3 strings characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; state \"main\" { // who are the characters? Console . print ( \"The characters are:\" ); Console . print ( characters [ 0 ]); // will print Surge Console . print ( characters [ 1 ]); // will print Neon Console . print ( characters [ 2 ]); // will print Charge // how many characters? Console . print ( \"Number of characters:\" ); Console . print ( characters . length ); // will print 3 } } Arrays have many interesting properties and operations that you can see in the Language Reference .","title":"Arrays"},{"location":"tutorials/variables/#dictionaries","text":"Dictionaries are collections of key-value pairs. In some programming languages, these are known as associative arrays or hash tables. Here's the syntax: object \"Application\" { // A dictionary that stores the weight (kg) of each character weight = { \"Surge\" : 35 , \"Neon\" : 30 , \"Charge\" : 37.5 , \"Gimacian\" : 70 }; // print the weights state \"main\" { Console . print ( \"Surge weighs \" + weight [ \"Surge\" ] + \" kg.\" ); Console . print ( \"Neon weighs \" + weight [ \"Neon\" ] + \" kg.\" ); Console . print ( \"Charge weighs \" + weight [ \"Charge\" ] + \" kg.\" ); Console . print ( \"Gimacian weighs \" + weight [ \"Gimacian\" ] + \" kg.\" ); } } Dictionaries have many interesting properties and operations that you can see in the Language Reference . Caution! Whenever you define an array or a dictionary, you spawn a new object. You are advised to NOT define arrays or dictionaries within states, because the code within the states run continuously. New objects will be created at every frame, not just once. object \"Application\" { // arr will be instantiated once the object is created arr = [ 1 , 2 , 3 ]; // RIGHT! state \"main\" { // err is instantiated at every frame of the application, // thus memory is wasted with duplicate objects err = [ \"don't\" , \"do\" , \"this\" ]; // AVOID! } }","title":"Dictionaries"},{"location":"tutorials/variables/#casting","text":"You can use type-casting to change the type of values from number to string, from string to number, from boolean to string and so on. Casting values is as simple as calling Number(value) , String(value) or Boolean(value) . Example: // Convert string to number str = \"2\" ; val = Number ( str ); // val is 2 // Convert number to string val = 123 ; str = String ( val ); // str is \"123\" When converting an object to a string, SurgeScript will implicitly call object.toString() .","title":"Casting"},{"location":"tutorials/variables/#scoping","text":"Variables that are defined before any state or function are object-level variables. They can be accessed throughout the whole object. On the other hand, variables used exclusively inside states or functions are local variables . This means that their accessibility and lifespan is restricted to their own locus of code. object \"Scope Test\" { name = \"Surge the Rabbit\" ; // object-level variable state \"main\" { weight = 35 ; // local variable state = \"print-data\" ; // change the state } state \"print-data\" { Console . print ( name ); // Surge the Rabbit Console . print ( weight ); // ERROR: weight is not defined } } Furthermore, object-level variables may only be accessed within the object. Other objects may not read or write the variables directly (in other words, variables are private to the objects). You need to define functions or getters and setters to accomplish that.","title":"Scoping"}]}
\ No newline at end of file
+{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Welcome to SurgeScript! Unleash your creativity! SurgeScript is a scripting language for games. Use it to unleash your creativity and build your own amazing interactive content! It's such a joy to use SurgeScript! You will love it! GET STARTED How do I learn SurgeScript? Check out the SurgeScript Crash Course ! Additionally, take a look at the video tutorials and at the examples that come with the software. SurgeScript in a nutshell SurgeScript is: A scripting language for games Easy for beginners, powerful for experts Object-oriented, dynamically typed and based on state machines Free and open-source software Built in C, which is nearly universal Named after a really charismatic character: Surge the Rabbit ! Why use SurgeScript? Unlike other programming languages, SurgeScript has been designed with the specific needs of games in mind. Its features include: The state-machine pattern: objects are state machines, making it easy to create game entities The composition approach: you may design complex objects and behaviors by means of composition The hierarchy system: objects have a parent and may have children, in a tree-like structure The game loop: it's defined implicitly Automatic garbage collection, object tagging and more! SurgeScript is meant to be used in games and in interactive applications. It's easy to integrate it into existing code, it's easy to extend it, it features a C-like syntax, and it's free and open-source software. SurgeScript has been designed based on the experience of its developer dealing with game engines, applications related to computer graphics and so on. Some of the best practices have been incorporated into the language itself, making things really easy for developers and modders. Who created SurgeScript? SurgeScript has been created by Alexandre Martins , a computer scientist from Brazil. He has also created the Open Surge game engine , hence the name SurgeScript.","title":"Introduction"},{"location":"#welcome-to-surgescript","text":"","title":"Welcome to SurgeScript!"},{"location":"#unleash-your-creativity","text":"SurgeScript is a scripting language for games. Use it to unleash your creativity and build your own amazing interactive content! It's such a joy to use SurgeScript! You will love it! GET STARTED","title":"Unleash your creativity!"},{"location":"#how-do-i-learn-surgescript","text":"Check out the SurgeScript Crash Course ! Additionally, take a look at the video tutorials and at the examples that come with the software.","title":"How do I learn SurgeScript?"},{"location":"#surgescript-in-a-nutshell","text":"SurgeScript is: A scripting language for games Easy for beginners, powerful for experts Object-oriented, dynamically typed and based on state machines Free and open-source software Built in C, which is nearly universal Named after a really charismatic character: Surge the Rabbit !","title":"SurgeScript in a nutshell"},{"location":"#why-use-surgescript","text":"Unlike other programming languages, SurgeScript has been designed with the specific needs of games in mind. Its features include: The state-machine pattern: objects are state machines, making it easy to create game entities The composition approach: you may design complex objects and behaviors by means of composition The hierarchy system: objects have a parent and may have children, in a tree-like structure The game loop: it's defined implicitly Automatic garbage collection, object tagging and more! SurgeScript is meant to be used in games and in interactive applications. It's easy to integrate it into existing code, it's easy to extend it, it features a C-like syntax, and it's free and open-source software. SurgeScript has been designed based on the experience of its developer dealing with game engines, applications related to computer graphics and so on. Some of the best practices have been incorporated into the language itself, making things really easy for developers and modders.","title":"Why use SurgeScript?"},{"location":"#who-created-surgescript","text":"SurgeScript has been created by Alexandre Martins , a computer scientist from Brazil. He has also created the Open Surge game engine , hence the name SurgeScript.","title":"Who created SurgeScript?"},{"location":"download/","text":"Download SurgeScript There are two ways to get SurgeScript: The first is to get Open Surge . This is recommended for most users. The second is to get the standalone version of the language. Open Surge To get Open Surge, visit opensurge2d.org and follow the instructions there. When you get Open Surge, you also get a full game engine featuring SurgeScript. This allows you to create your own scripts and games with plenty of interactivity and ease. Once you download Open Surge, the next step is to create your first script . Standalone version To get the standalone version, go to the SurgeScript page on GitHub . There you'll find instructions on how to compile SurgeScript. When you compile SurgeScript, you'll end up with a text-only program. There are no graphics and no game engine is attached to it. You can try your scripts using the command line. Once you get the standalone version, the next step is to create your first script .","title":"Download"},{"location":"download/#download-surgescript","text":"There are two ways to get SurgeScript: The first is to get Open Surge . This is recommended for most users. The second is to get the standalone version of the language.","title":"Download SurgeScript"},{"location":"download/#open-surge","text":"To get Open Surge, visit opensurge2d.org and follow the instructions there. When you get Open Surge, you also get a full game engine featuring SurgeScript. This allows you to create your own scripts and games with plenty of interactivity and ease. Once you download Open Surge, the next step is to create your first script .","title":"Open Surge"},{"location":"download/#standalone-version","text":"To get the standalone version, go to the SurgeScript page on GitHub . There you'll find instructions on how to compile SurgeScript. When you compile SurgeScript, you'll end up with a text-only program. There are no graphics and no game engine is attached to it. You can try your scripts using the command line. Once you get the standalone version, the next step is to create your first script .","title":"Standalone version"},{"location":"engine/actor/","text":"Actor The Actor component is used to associate a sprite to a target object. The target object is required to be an entity . It's recommended to use only one actor per entity. Factory Actor Actor(sprite) Spawns a new Actor component with the given sprite name. Arguments sprite : string. The name of the sprite (defined in the sprites/ folder). Returns An Actor component. Example using SurgeEngine.Actor ; object \"SurgeTest\" is \"entity\" { // spawns an Actor with the SurgeTest sprite actor = Actor ( \"SurgeTest\" ); state \"main\" { } } Properties anim anim : number. A shortcut to animation.id : an integer corresponding to the animation number. Defaults to 0. animation animation : Animation object, read-only. Reference to the Animation object of the Actor. entity entity : object, read-only. The entity associated with this component. hflip hflip : boolean. Should the actor be flipped horizontally? Defaults to false . vflip vflip : boolean. Should the actor be flipped vertically? Defaults to false . visible visible : boolean. Should the actor be rendered? Defaults to true . alpha alpha : number. Opacity value, ranging from zero (0% opaque) to one (100% opaque). Defaults to 1.0. offset offset : Vector2 object. A (x,y) offset relative to the parent object. Defaults to zero. anchor anchor : Vector2 object. A shortcut to animation.anchor . See also: anchor . Available since: Open Surge 0.6.0 hotSpot hotSpot : Vector2 object. A shortcut to animation.hotSpot . See also: hot spot . Available since: Open Surge 0.6.0. In versions prior to 0.6.0, you may get the hot spot using the Animation object. actionSpot actionSpot : Vector2 object. A shortcut to animation.actionSpot . See also: action spot . Available since: Open Surge 0.6.0 actionOffset actionOffset : Vector2 object, read-only. A shortcut to animation.actionOffset . See also: action offset . Available since: Open Surge 0.6.0 width width : number, read-only. The width of the actor. height height : number, read-only. The height of the actor. zindex zindex : number. Objects with greater zindex are rendered in front of others. Defaults to 0.5.","title":"Actor"},{"location":"engine/actor/#actor","text":"The Actor component is used to associate a sprite to a target object. The target object is required to be an entity . It's recommended to use only one actor per entity.","title":"Actor"},{"location":"engine/actor/#factory","text":"","title":"Factory"},{"location":"engine/actor/#actor_1","text":"Actor(sprite) Spawns a new Actor component with the given sprite name. Arguments sprite : string. The name of the sprite (defined in the sprites/ folder). Returns An Actor component. Example using SurgeEngine.Actor ; object \"SurgeTest\" is \"entity\" { // spawns an Actor with the SurgeTest sprite actor = Actor ( \"SurgeTest\" ); state \"main\" { } }","title":"Actor"},{"location":"engine/actor/#properties","text":"","title":"Properties"},{"location":"engine/actor/#anim","text":"anim : number. A shortcut to animation.id : an integer corresponding to the animation number. Defaults to 0.","title":"anim"},{"location":"engine/actor/#animation","text":"animation : Animation object, read-only. Reference to the Animation object of the Actor.","title":"animation"},{"location":"engine/actor/#entity","text":"entity : object, read-only. The entity associated with this component.","title":"entity"},{"location":"engine/actor/#hflip","text":"hflip : boolean. Should the actor be flipped horizontally? Defaults to false .","title":"hflip"},{"location":"engine/actor/#vflip","text":"vflip : boolean. Should the actor be flipped vertically? Defaults to false .","title":"vflip"},{"location":"engine/actor/#visible","text":"visible : boolean. Should the actor be rendered? Defaults to true .","title":"visible"},{"location":"engine/actor/#alpha","text":"alpha : number. Opacity value, ranging from zero (0% opaque) to one (100% opaque). Defaults to 1.0.","title":"alpha"},{"location":"engine/actor/#offset","text":"offset : Vector2 object. A (x,y) offset relative to the parent object. Defaults to zero.","title":"offset"},{"location":"engine/actor/#anchor","text":"anchor : Vector2 object. A shortcut to animation.anchor . See also: anchor . Available since: Open Surge 0.6.0","title":"anchor"},{"location":"engine/actor/#hotspot","text":"hotSpot : Vector2 object. A shortcut to animation.hotSpot . See also: hot spot . Available since: Open Surge 0.6.0. In versions prior to 0.6.0, you may get the hot spot using the Animation object.","title":"hotSpot"},{"location":"engine/actor/#actionspot","text":"actionSpot : Vector2 object. A shortcut to animation.actionSpot . See also: action spot . Available since: Open Surge 0.6.0","title":"actionSpot"},{"location":"engine/actor/#actionoffset","text":"actionOffset : Vector2 object, read-only. A shortcut to animation.actionOffset . See also: action offset . Available since: Open Surge 0.6.0","title":"actionOffset"},{"location":"engine/actor/#width","text":"width : number, read-only. The width of the actor.","title":"width"},{"location":"engine/actor/#height","text":"height : number, read-only. The height of the actor.","title":"height"},{"location":"engine/actor/#zindex","text":"zindex : number. Objects with greater zindex are rendered in front of others. Defaults to 0.5.","title":"zindex"},{"location":"engine/androidplatform/","text":"AndroidPlatform Routines specific to Android. The functions below do nothing if the engine is not running on it. In order to determine if the engine is running on Android, check Platform.isAndroid . Available since: Open Surge 0.6.1 Functions shareText shareText(text) Share a text using the Android Sharesheet, a feature that lets the user pick which app to share data with. You may use it to let the user share a URL with a friend or on social media, for example. Arguments text : string. The text to be shared. Example using SurgeEngine.Platform ; using SurgeEngine.Platform.Android ; // ... if ( Platform . isAndroid ) Android . shareText ( \"Download the Open Surge Engine at https://opensurge2d.org\" );","title":"Android"},{"location":"engine/androidplatform/#androidplatform","text":"Routines specific to Android. The functions below do nothing if the engine is not running on it. In order to determine if the engine is running on Android, check Platform.isAndroid . Available since: Open Surge 0.6.1","title":"AndroidPlatform"},{"location":"engine/androidplatform/#functions","text":"","title":"Functions"},{"location":"engine/androidplatform/#sharetext","text":"shareText(text) Share a text using the Android Sharesheet, a feature that lets the user pick which app to share data with. You may use it to let the user share a URL with a friend or on social media, for example. Arguments text : string. The text to be shared. Example using SurgeEngine.Platform ; using SurgeEngine.Platform.Android ; // ... if ( Platform . isAndroid ) Android . shareText ( \"Download the Open Surge Engine at https://opensurge2d.org\" );","title":"shareText"},{"location":"engine/animation/","text":"Animation Animation objects are used to gather data about specific animations. Although you can't spawn Animation objects directly, you can access them via other objects such as Actor and Player . Example using SurgeEngine.Actor ; object \"MyExplosion\" is \"entity\" , \"disposable\" , \"private\" { actor = Actor ( \"MyExplosion\" ); state \"main\" { if ( actor . animation . finished ) destroy (); } } Properties id id : number. The number of the animation, defined in a .spr file. sprite sprite : string, read-only. The name of the sprite, defined in a .spr file. exists exists : boolean, read-only. Will be true if the animation exists, i.e., if its sprite and its animation number have been defined in a .spr file. Available since: Open Surge 0.5.1 finished finished : boolean, read-only. Will be true if the animation has finished playing. anchor anchor : Vector2 object, read-only. The hot spot of the animation normalized to [0,1] x [0,1]. Available since: Open Surge 0.6.0 hotSpot hotSpot : Vector2 object, read-only. The hot spot of the animation. Coordinates are given in pixels. Note: prior to Open Surge 0.6.0, this property was called hotspot . actionSpot actionSpot : Vector2 object, read-only. The action spot of the animation. Coordinates are given in pixels. If the sprite is flipped, the action spot is automatically flipped relative to the hot spot of the animation. Available since: Open Surge 0.6.0 actionOffset actionOffset : Vector2 object, read-only. When this vector is added to the position of the sprite, you'll get the position of the action spot . This is suitable to be used with transform.localPosition . Available since: Open Surge 0.6.0 repeats repeats : boolean, read-only. Does the animation repeat itself? fps fps : number, read-only. Frames per second of the animation. frameCount frameCount : number, read-only. The number of frames of the animation. duration duration : number, read-only. The duration of the animation, in seconds. Available since: Open Surge 0.6.1 frame frame : number. The current frame of the animation: an integer between 0 and frameCount - 1 , inclusive. speedFactor speedFactor : number. While the FPS rate controls the speed of the animation, the speed factor gives you an additional degree of control. This is a multiplier that defaults to 1.0, meaning that the animation will run using its normal speed. If it's set to 2.0, it will run using twice that speed. A value of 0.5 means half the speed, and so on. sync sync : boolean. Is the animation is synchronized? A synchronized animation is a repeating animation that displays the same frame across multiple sprites. Defaults to false . Functions prop prop(propertyName) Read the user-defined custom property named propertyName defined in a custom_properties block of the sprite of this animation (.spr file). If the property exists, this function will return a string, a number, a boolean, or an Array of these, depending on the property. If the property does not exist, this function will return null . Available since: Open Surge 0.6.1 Arguments propertyName : string. The name of a custom property. Returns Returns a string, a number, a boolean, an array of these primitive types with at least two elements, or null . Example /* Example of a custom_properties block: // .spr file sprite \"My Test Sprite\" { // ... custom_properties { number_of_layers 8 want_awesomeness true font_name \"GoodNeighbors\" position 100 200 } } */ // It's a good idea to cast the value of the property to the expected type, so // that your script will work reliably regardless of what is in the .spr file! animation = actor . animation ; numberOfLayers = Number ( animation . prop ( \"number_of_layers\" )); // 8 wantAwesomeness = Boolean ( animation . prop ( \"want_awesomeness\" )); // true fontName = String ( animation . prop ( \"font_name\" ) || \"Default Font Name\" ); // \"GoodNeighbors\" foobar = String ( animation . prop ( \"foobar\" ) || \"undefined\" ); // \"undefined\" position = animation . prop ( \"position\" ); if ( typeof position == \"object\" ) { xpos = Number ( position [ 0 ]); // 100 ypos = Number ( position [ 1 ]); // 200 } else { xpos = 0 ; ypos = 0 ; } findTransform findTransform() When a keyframe-based animation is playing, compute an approximation of the transformation applied to the sprite at the current time. You may use this function to make objects follow the transformed sprite or to know its location. If no keyframe-based animation is currently playing, the identity transform will be returned. Available since: Open Surge 0.6.1 Returns Returns a Transform object. Example animationTransform = animation . findTransform (); Console . print ( animationTransform . localPosition );","title":"Animation"},{"location":"engine/animation/#animation","text":"Animation objects are used to gather data about specific animations. Although you can't spawn Animation objects directly, you can access them via other objects such as Actor and Player . Example using SurgeEngine.Actor ; object \"MyExplosion\" is \"entity\" , \"disposable\" , \"private\" { actor = Actor ( \"MyExplosion\" ); state \"main\" { if ( actor . animation . finished ) destroy (); } }","title":"Animation"},{"location":"engine/animation/#properties","text":"","title":"Properties"},{"location":"engine/animation/#id","text":"id : number. The number of the animation, defined in a .spr file.","title":"id"},{"location":"engine/animation/#sprite","text":"sprite : string, read-only. The name of the sprite, defined in a .spr file.","title":"sprite"},{"location":"engine/animation/#exists","text":"exists : boolean, read-only. Will be true if the animation exists, i.e., if its sprite and its animation number have been defined in a .spr file. Available since: Open Surge 0.5.1","title":"exists"},{"location":"engine/animation/#finished","text":"finished : boolean, read-only. Will be true if the animation has finished playing.","title":"finished"},{"location":"engine/animation/#anchor","text":"anchor : Vector2 object, read-only. The hot spot of the animation normalized to [0,1] x [0,1]. Available since: Open Surge 0.6.0","title":"anchor"},{"location":"engine/animation/#hotspot","text":"hotSpot : Vector2 object, read-only. The hot spot of the animation. Coordinates are given in pixels. Note: prior to Open Surge 0.6.0, this property was called hotspot .","title":"hotSpot"},{"location":"engine/animation/#actionspot","text":"actionSpot : Vector2 object, read-only. The action spot of the animation. Coordinates are given in pixels. If the sprite is flipped, the action spot is automatically flipped relative to the hot spot of the animation. Available since: Open Surge 0.6.0","title":"actionSpot"},{"location":"engine/animation/#actionoffset","text":"actionOffset : Vector2 object, read-only. When this vector is added to the position of the sprite, you'll get the position of the action spot . This is suitable to be used with transform.localPosition . Available since: Open Surge 0.6.0","title":"actionOffset"},{"location":"engine/animation/#repeats","text":"repeats : boolean, read-only. Does the animation repeat itself?","title":"repeats"},{"location":"engine/animation/#fps","text":"fps : number, read-only. Frames per second of the animation.","title":"fps"},{"location":"engine/animation/#framecount","text":"frameCount : number, read-only. The number of frames of the animation.","title":"frameCount"},{"location":"engine/animation/#duration","text":"duration : number, read-only. The duration of the animation, in seconds. Available since: Open Surge 0.6.1","title":"duration"},{"location":"engine/animation/#frame","text":"frame : number. The current frame of the animation: an integer between 0 and frameCount - 1 , inclusive.","title":"frame"},{"location":"engine/animation/#speedfactor","text":"speedFactor : number. While the FPS rate controls the speed of the animation, the speed factor gives you an additional degree of control. This is a multiplier that defaults to 1.0, meaning that the animation will run using its normal speed. If it's set to 2.0, it will run using twice that speed. A value of 0.5 means half the speed, and so on.","title":"speedFactor"},{"location":"engine/animation/#sync","text":"sync : boolean. Is the animation is synchronized? A synchronized animation is a repeating animation that displays the same frame across multiple sprites. Defaults to false .","title":"sync"},{"location":"engine/animation/#functions","text":"","title":"Functions"},{"location":"engine/animation/#prop","text":"prop(propertyName) Read the user-defined custom property named propertyName defined in a custom_properties block of the sprite of this animation (.spr file). If the property exists, this function will return a string, a number, a boolean, or an Array of these, depending on the property. If the property does not exist, this function will return null . Available since: Open Surge 0.6.1 Arguments propertyName : string. The name of a custom property. Returns Returns a string, a number, a boolean, an array of these primitive types with at least two elements, or null . Example /* Example of a custom_properties block: // .spr file sprite \"My Test Sprite\" { // ... custom_properties { number_of_layers 8 want_awesomeness true font_name \"GoodNeighbors\" position 100 200 } } */ // It's a good idea to cast the value of the property to the expected type, so // that your script will work reliably regardless of what is in the .spr file! animation = actor . animation ; numberOfLayers = Number ( animation . prop ( \"number_of_layers\" )); // 8 wantAwesomeness = Boolean ( animation . prop ( \"want_awesomeness\" )); // true fontName = String ( animation . prop ( \"font_name\" ) || \"Default Font Name\" ); // \"GoodNeighbors\" foobar = String ( animation . prop ( \"foobar\" ) || \"undefined\" ); // \"undefined\" position = animation . prop ( \"position\" ); if ( typeof position == \"object\" ) { xpos = Number ( position [ 0 ]); // 100 ypos = Number ( position [ 1 ]); // 200 } else { xpos = 0 ; ypos = 0 ; }","title":"prop"},{"location":"engine/animation/#findtransform","text":"findTransform() When a keyframe-based animation is playing, compute an approximation of the transformation applied to the sprite at the current time. You may use this function to make objects follow the transformed sprite or to know its location. If no keyframe-based animation is currently playing, the identity transform will be returned. Available since: Open Surge 0.6.1 Returns Returns a Transform object. Example animationTransform = animation . findTransform (); Console . print ( animationTransform . localPosition );","title":"findTransform"},{"location":"engine/behavior/","text":"Behavior A behavior is an object that, when spawned as a child of an entity , adds a specific behavior to that entity. Example: you can add a behavior to give a Directional Movement to an entity, so you don't need to code that movement yourself. Although the use of behaviors is not mandatory, they greatly simplify the development of your entities. An important aspect of using behaviors is that you can create your own. You can also reuse them in many of your entities and share them with others. Behavior objects should be built in a generic way, so that they can be reused throughout multiple entities. Behavior objects must be tagged behavior and are supposed to be spawned as direct children of entities. They should also implement the protocol (properties, methods) described below. The engine provides a few behaviors by default, and they have been documented in this manual. Example // // The example below shows an entity with 2 behaviors: // // - Enemy: it makes the entity behave like an enemy // (it can hit the player, or be defeated) // // - DirectionalMovement: it makes the entity move // in a certain direction, with a certain speed // using SurgeEngine.Actor ; using SurgeEngine.Vector2 ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.DirectionalMovement ; // Mosquito is a flying baddie object \"Mosquito\" is \"entity\" , \"enemy\" { actor = Actor ( \"Mosquito\" ); enemy = Enemy (); movement = DirectionalMovement (); state \"main\" { actor . hflip = true ; // flip the sprite horizontally movement . direction = Vector2 . left ; movement . speed = 60 ; } } Properties entity entity : object, read-only. The entity associated with this behavior. This is a convenient alias to the parent object. enabled enabled : boolean. Is the behavior enabled? The default value is true , i.e., behaviors are enabled by default.","title":"Behavior"},{"location":"engine/behavior/#behavior","text":"A behavior is an object that, when spawned as a child of an entity , adds a specific behavior to that entity. Example: you can add a behavior to give a Directional Movement to an entity, so you don't need to code that movement yourself. Although the use of behaviors is not mandatory, they greatly simplify the development of your entities. An important aspect of using behaviors is that you can create your own. You can also reuse them in many of your entities and share them with others. Behavior objects should be built in a generic way, so that they can be reused throughout multiple entities. Behavior objects must be tagged behavior and are supposed to be spawned as direct children of entities. They should also implement the protocol (properties, methods) described below. The engine provides a few behaviors by default, and they have been documented in this manual. Example // // The example below shows an entity with 2 behaviors: // // - Enemy: it makes the entity behave like an enemy // (it can hit the player, or be defeated) // // - DirectionalMovement: it makes the entity move // in a certain direction, with a certain speed // using SurgeEngine.Actor ; using SurgeEngine.Vector2 ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.DirectionalMovement ; // Mosquito is a flying baddie object \"Mosquito\" is \"entity\" , \"enemy\" { actor = Actor ( \"Mosquito\" ); enemy = Enemy (); movement = DirectionalMovement (); state \"main\" { actor . hflip = true ; // flip the sprite horizontally movement . direction = Vector2 . left ; movement . speed = 60 ; } }","title":"Behavior"},{"location":"engine/behavior/#properties","text":"","title":"Properties"},{"location":"engine/behavior/#entity","text":"entity : object, read-only. The entity associated with this behavior. This is a convenient alias to the parent object.","title":"entity"},{"location":"engine/behavior/#enabled","text":"enabled : boolean. Is the behavior enabled? The default value is true , i.e., behaviors are enabled by default.","title":"enabled"},{"location":"engine/brick/","text":"Brick The Brick component is used to create brick-like objects, or bricks endowed with scripting capabilities. This allows you to create elevators, conditional barriers (e.g., doors), movable platforms with custom trajectories, and much more. The Brick component only affects collisions. The object that uses it is required to be an entity . This component won't do any rendering. Therefore, it's typically used in conjunction with the Actor component. Example using SurgeEngine.Actor ; using SurgeEngine.Brick ; object \"On/Off Platform\" is \"entity\" { actor = Actor ( \"On/Off Platform\" ); // for rendering brick = Brick ( \"On/Off Platform\" ); // for collision state \"main\" { if ( timeout ( 2.0 )) { brick . enabled = false ; actor . visible = false ; state = \"disabled\" ; } } state \"disabled\" { if ( timeout ( 2.0 )) { brick . enabled = true ; actor . visible = true ; state = \"main\" ; } } } Factory Brick Brick(spriteName) Spawns a new Brick component. Just like regular bricks, a Brick component has a collision mask associated with it. By default, the collision mask will be computed according to the animation 0 of the sprite named spriteName . Arguments spriteName : string. The name of a sprite. Returns A new Brick component. Properties enabled enabled : boolean. Whether the Brick component should affect collisions or not. Defaults to true . type type : string. The type of the Brick component specifies how it affects collisions. This value must be either \"solid\" or \"cloud\" . Defaults to \"solid\" . layer layer : string. Should the Brick component be tied to a specific layer? If so, which layer? This value must be one of the following: \"green\" , \"yellow\" , \"default\" . Defaults to \"default\" . offset offset : Vector2 object. A (x,y) offset relative to the parent object. Defaults to zero.","title":"Brick"},{"location":"engine/brick/#brick","text":"The Brick component is used to create brick-like objects, or bricks endowed with scripting capabilities. This allows you to create elevators, conditional barriers (e.g., doors), movable platforms with custom trajectories, and much more. The Brick component only affects collisions. The object that uses it is required to be an entity . This component won't do any rendering. Therefore, it's typically used in conjunction with the Actor component. Example using SurgeEngine.Actor ; using SurgeEngine.Brick ; object \"On/Off Platform\" is \"entity\" { actor = Actor ( \"On/Off Platform\" ); // for rendering brick = Brick ( \"On/Off Platform\" ); // for collision state \"main\" { if ( timeout ( 2.0 )) { brick . enabled = false ; actor . visible = false ; state = \"disabled\" ; } } state \"disabled\" { if ( timeout ( 2.0 )) { brick . enabled = true ; actor . visible = true ; state = \"main\" ; } } }","title":"Brick"},{"location":"engine/brick/#factory","text":"","title":"Factory"},{"location":"engine/brick/#brick_1","text":"Brick(spriteName) Spawns a new Brick component. Just like regular bricks, a Brick component has a collision mask associated with it. By default, the collision mask will be computed according to the animation 0 of the sprite named spriteName . Arguments spriteName : string. The name of a sprite. Returns A new Brick component.","title":"Brick"},{"location":"engine/brick/#properties","text":"","title":"Properties"},{"location":"engine/brick/#enabled","text":"enabled : boolean. Whether the Brick component should affect collisions or not. Defaults to true .","title":"enabled"},{"location":"engine/brick/#type","text":"type : string. The type of the Brick component specifies how it affects collisions. This value must be either \"solid\" or \"cloud\" . Defaults to \"solid\" .","title":"type"},{"location":"engine/brick/#layer","text":"layer : string. Should the Brick component be tied to a specific layer? If so, which layer? This value must be one of the following: \"green\" , \"yellow\" , \"default\" . Defaults to \"default\" .","title":"layer"},{"location":"engine/brick/#offset","text":"offset : Vector2 object. A (x,y) offset relative to the parent object. Defaults to zero.","title":"offset"},{"location":"engine/camera/","text":"Camera The Camera object can be used to control what content, in world space, is rendered to the screen. The Camera is represented by a 2-dimensional point in world space that is mapped to the center of the screen. Detached entities Entities tagged \"detached\" do not follow the camera. They are rendered in screen space, not in world space. This is useful for creating HUD elements ( Heads-Up Display ). Read more about entities . Example // Import the Camera object using SurgeEngine.Camera ; // Reading the Camera status // This object prints the position of the camera at every second object \"Camera Status\" is \"awake\" , \"entity\" { state \"main\" { if ( timeout ( 1 )) state = \"print\" ; } state \"print\" { Console . print ( Camera . position ); state = \"main\" ; } } Properties position position : Vector2 object. The position of the camera in world space. Tip: use lateUpdate() if you need to change it. Example using SurgeEngine.Camera ; using SurgeEngine.Player ; object \"My Simple Camera\" is \"awake\" , \"entity\" { fun lateUpdate () { player = Player . active ; Camera . position = player . transform . position ; } } locked locked : boolean, read-only. Is the camera locked to a certain area in space? Defaults to false . Functions lock lock(left, top, right, bottom) Locks the camera to a certain rectangular area in space. All coordinates are given in pixels and represent the boundaries of the rectangular area. They are such that left <= right and top <= bottom . Arguments left : number. A x-coordinate in world space. top : number. A y-coordinate in world space. right : number. A x-coordinate in world space. bottom : number. A y-coordinate in world space. unlock unlock() Unlocks the camera. If unlocked, the camera moves freely throughout the space. worldToScreen worldToScreen(position) Converts position from world space to screen space. Screen coordinates are given in pixels. (0,0) is the top-left of the screen and ( Screen.width , Screen.height ) is the bottom-right. Available since: Open Surge 0.5.1 Arguments position : Vector2 object. The position to be converted. Returns Returns a Vector2 object corresponding to the converted coordinates. screenToWorld screenToWorld(position) Converts position from screen space to world space. Screen coordinates are given in pixels. (0,0) is the top-left of the screen and ( Screen.width , Screen.height ) is the bottom-right. Available since: Open Surge 0.5.1 Arguments position : Vector2 object. The position to be converted. Returns Returns a Vector2 object corresponding to the converted coordinates.","title":"Camera"},{"location":"engine/camera/#camera","text":"The Camera object can be used to control what content, in world space, is rendered to the screen. The Camera is represented by a 2-dimensional point in world space that is mapped to the center of the screen. Detached entities Entities tagged \"detached\" do not follow the camera. They are rendered in screen space, not in world space. This is useful for creating HUD elements ( Heads-Up Display ). Read more about entities . Example // Import the Camera object using SurgeEngine.Camera ; // Reading the Camera status // This object prints the position of the camera at every second object \"Camera Status\" is \"awake\" , \"entity\" { state \"main\" { if ( timeout ( 1 )) state = \"print\" ; } state \"print\" { Console . print ( Camera . position ); state = \"main\" ; } }","title":"Camera"},{"location":"engine/camera/#properties","text":"","title":"Properties"},{"location":"engine/camera/#position","text":"position : Vector2 object. The position of the camera in world space. Tip: use lateUpdate() if you need to change it. Example using SurgeEngine.Camera ; using SurgeEngine.Player ; object \"My Simple Camera\" is \"awake\" , \"entity\" { fun lateUpdate () { player = Player . active ; Camera . position = player . transform . position ; } }","title":"position"},{"location":"engine/camera/#locked","text":"locked : boolean, read-only. Is the camera locked to a certain area in space? Defaults to false .","title":"locked"},{"location":"engine/camera/#functions","text":"","title":"Functions"},{"location":"engine/camera/#lock","text":"lock(left, top, right, bottom) Locks the camera to a certain rectangular area in space. All coordinates are given in pixels and represent the boundaries of the rectangular area. They are such that left <= right and top <= bottom . Arguments left : number. A x-coordinate in world space. top : number. A y-coordinate in world space. right : number. A x-coordinate in world space. bottom : number. A y-coordinate in world space.","title":"lock"},{"location":"engine/camera/#unlock","text":"unlock() Unlocks the camera. If unlocked, the camera moves freely throughout the space.","title":"unlock"},{"location":"engine/camera/#worldtoscreen","text":"worldToScreen(position) Converts position from world space to screen space. Screen coordinates are given in pixels. (0,0) is the top-left of the screen and ( Screen.width , Screen.height ) is the bottom-right. Available since: Open Surge 0.5.1 Arguments position : Vector2 object. The position to be converted. Returns Returns a Vector2 object corresponding to the converted coordinates.","title":"worldToScreen"},{"location":"engine/camera/#screentoworld","text":"screenToWorld(position) Converts position from screen space to world space. Screen coordinates are given in pixels. (0,0) is the top-left of the screen and ( Screen.width , Screen.height ) is the bottom-right. Available since: Open Surge 0.5.1 Arguments position : Vector2 object. The position to be converted. Returns Returns a Vector2 object corresponding to the converted coordinates.","title":"screenToWorld"},{"location":"engine/circular_movement/","text":"Circular Movement The Circular Movement behavior makes the associated entity perform a circular orbit on the 2D plane. Its basic parameters are: A radius, given in pixels A movement rate, given in cycles per second Other parameters include: a movement scale in both X and Y axes (making it an elliptic orbit), a flag telling whether the movement should be clockwise or not, and so on. Example // // The example below shows how to make an entity move along // a circle of 128 pixels of radius at a rate of 0.25 cycles // per second (i.e., it takes one second to complete 25% of // a cycle, or 4 seconds to complete a cycle) // using SurgeEngine.Actor ; using SurgeEngine.Vector2 ; using SurgeEngine.Behaviors.CircularMovement ; object \"Simple Ball\" is \"entity\" { actor = Actor ( \"Simple Ball\" ); movement = CircularMovement (); state \"main\" { movement . radius = 128 ; movement . rate = 0.25 ; //movement.scale = Vector2.up; // uncomment to move along the y-axis only } } Factory Behaviors.CircularMovement CircularMovement() Spawns a CircularMovement. Returns A CircularMovement object. Properties radius radius : number. The radius of the movement, in pixels. rate rate : number. The rate of the movement, given in cycles per second. clockwise clockwise : boolean. Indicates whether the movement is clockwise ( true ) or counterclockwise ( false ). Defaults to false . scale scale : Vector2 object. Specifies the scale of the movement in both X and Y axes. It is used to distort the circle. Vector2(1, 1) means no distortion (default). center center : Vector2 object | null . If not null , forces the center of the movement to be at a particular position in world space. Defaults to null . phaseOffset phaseOffset : number. A value in degrees that offsets the current phase . Defaults to zero (180 means opposite phase relative to zero). phase phase : number, read-only. A value in degrees that indicates the current phase of the movement.","title":"CircularMovement"},{"location":"engine/circular_movement/#circular-movement","text":"The Circular Movement behavior makes the associated entity perform a circular orbit on the 2D plane. Its basic parameters are: A radius, given in pixels A movement rate, given in cycles per second Other parameters include: a movement scale in both X and Y axes (making it an elliptic orbit), a flag telling whether the movement should be clockwise or not, and so on. Example // // The example below shows how to make an entity move along // a circle of 128 pixels of radius at a rate of 0.25 cycles // per second (i.e., it takes one second to complete 25% of // a cycle, or 4 seconds to complete a cycle) // using SurgeEngine.Actor ; using SurgeEngine.Vector2 ; using SurgeEngine.Behaviors.CircularMovement ; object \"Simple Ball\" is \"entity\" { actor = Actor ( \"Simple Ball\" ); movement = CircularMovement (); state \"main\" { movement . radius = 128 ; movement . rate = 0.25 ; //movement.scale = Vector2.up; // uncomment to move along the y-axis only } }","title":"Circular Movement"},{"location":"engine/circular_movement/#factory","text":"","title":"Factory"},{"location":"engine/circular_movement/#behaviorscircularmovement","text":"CircularMovement() Spawns a CircularMovement. Returns A CircularMovement object.","title":"Behaviors.CircularMovement"},{"location":"engine/circular_movement/#properties","text":"","title":"Properties"},{"location":"engine/circular_movement/#radius","text":"radius : number. The radius of the movement, in pixels.","title":"radius"},{"location":"engine/circular_movement/#rate","text":"rate : number. The rate of the movement, given in cycles per second.","title":"rate"},{"location":"engine/circular_movement/#clockwise","text":"clockwise : boolean. Indicates whether the movement is clockwise ( true ) or counterclockwise ( false ). Defaults to false .","title":"clockwise"},{"location":"engine/circular_movement/#scale","text":"scale : Vector2 object. Specifies the scale of the movement in both X and Y axes. It is used to distort the circle. Vector2(1, 1) means no distortion (default).","title":"scale"},{"location":"engine/circular_movement/#center","text":"center : Vector2 object | null . If not null , forces the center of the movement to be at a particular position in world space. Defaults to null .","title":"center"},{"location":"engine/circular_movement/#phaseoffset","text":"phaseOffset : number. A value in degrees that offsets the current phase . Defaults to zero (180 means opposite phase relative to zero).","title":"phaseOffset"},{"location":"engine/circular_movement/#phase","text":"phase : number, read-only. A value in degrees that indicates the current phase of the movement.","title":"phase"},{"location":"engine/collider/","text":"Collider A collider, or collision object, is used to detect collisions. There are different types of colliders, each with a different shape. They are usually centered on the hot spot of sprites, but that can be changed by altering their anchor . Colliders must be spawned as children of entities . To detect collisions, you may implement function onCollision() on the entity (see the example below), or use the colliders directly. Additionally, a single entity may have multiple colliders attached to it. This allows users to work with more complex shapes than simple primitives. A collider is an abstract concept, and hence can't be spawned directly. Rather, you can spawn colliders of specific shapes, such as CollisionBox and CollisionBall . All Colliders share some functionalities (detailed in this page), but there are functionalities tied to specific shapes. Example using SurgeEngine.Actor ; using SurgeEngine.Player ; using SurgeEngine.Collisions.CollisionBall ; object \"CollisionDoll\" is \"entity\" { actor = Actor ( \"CollisionDoll\" ); collider = CollisionBall ( 25 ); // ball with radius = 25px // The player has a built-in collider // Let's make it visible for debugging state \"main\" { player = Player . active ; player . collider . visible = true ; collider . visible = true ; } // Detect collisions between a collider that is a child // of this object and any other collider in the game fun onCollision ( otherCollider ) { // A collision has occurred. Console . print ( \"Collided with something\" ); // Collided with a player? if ( otherCollider . entity . hasTag ( \"player\" )) { player = otherCollider . entity ; Console . print ( \"Touched \" + player . name ); } } // While onCollision() catches the moment a collision // first occurs, onOverlap() is called every frame // this collider collides with other collider fun onOverlap ( otherCollider ) { // This function is optional. } } Properties entity entity : object, read-only. The Entity associated with this collider. enabled enabled : boolean. Is the collider enabled? A collider that is not enabled will not notify the parent object if a collision occurs. The default value is true , i.e., colliders are enabled by default. visible visible : boolean. Is the collider visible? This is useful for debugging. The default value is false . anchor anchor : Vector2 object. The anchor of the collider. See also: setAnchor . Available since: Open Surge 0.6.0 Functions collidesWith collidesWith(collider) Checks if this collider is colliding with some other collider. Arguments collider : Collider object. The other collider. Returns Returns true if there is a collision (the colliders overlap), or false otherwise. contains contains(point) Checks if the collider contains the given point, given in world coordinates. Arguments point : Vector2 object. The point to be tested. Returns Returns true if the point is contained in the collider, or false otherwise. setAnchor setAnchor(x, y) Defines the anchor of the collider to be ( x , y ), where these values are (usually) numbers between 0.0 and 1.0. Imagine a bounding box of the collider. Point (0.5, 0.5) is the default, representing its center. Point (0.0, 0.0) is the top-left and (1,0, 1.0), the bottom-right. The anchor of the collider will be aligned to the hot spot of the sprite of the entity. See also: anchor . Arguments x : number. Usually a value between 0.0 and 1.0. y : number. Usually a value between 0.0 and 1.0. Returns Returns the collider itself. Example // ... using SurgeEngine.Collisions.CollisionBox ; object \"CollisionTestObject\" is \"entity\" { // see that the following collision box // has its anchor on pixel (16, 64) collider = CollisionBox ( 32 , 64 ). setAnchor ( 0.5 , 1.0 ); // ... }","title":"Collider"},{"location":"engine/collider/#collider","text":"A collider, or collision object, is used to detect collisions. There are different types of colliders, each with a different shape. They are usually centered on the hot spot of sprites, but that can be changed by altering their anchor . Colliders must be spawned as children of entities . To detect collisions, you may implement function onCollision() on the entity (see the example below), or use the colliders directly. Additionally, a single entity may have multiple colliders attached to it. This allows users to work with more complex shapes than simple primitives. A collider is an abstract concept, and hence can't be spawned directly. Rather, you can spawn colliders of specific shapes, such as CollisionBox and CollisionBall . All Colliders share some functionalities (detailed in this page), but there are functionalities tied to specific shapes. Example using SurgeEngine.Actor ; using SurgeEngine.Player ; using SurgeEngine.Collisions.CollisionBall ; object \"CollisionDoll\" is \"entity\" { actor = Actor ( \"CollisionDoll\" ); collider = CollisionBall ( 25 ); // ball with radius = 25px // The player has a built-in collider // Let's make it visible for debugging state \"main\" { player = Player . active ; player . collider . visible = true ; collider . visible = true ; } // Detect collisions between a collider that is a child // of this object and any other collider in the game fun onCollision ( otherCollider ) { // A collision has occurred. Console . print ( \"Collided with something\" ); // Collided with a player? if ( otherCollider . entity . hasTag ( \"player\" )) { player = otherCollider . entity ; Console . print ( \"Touched \" + player . name ); } } // While onCollision() catches the moment a collision // first occurs, onOverlap() is called every frame // this collider collides with other collider fun onOverlap ( otherCollider ) { // This function is optional. } }","title":"Collider"},{"location":"engine/collider/#properties","text":"","title":"Properties"},{"location":"engine/collider/#entity","text":"entity : object, read-only. The Entity associated with this collider.","title":"entity"},{"location":"engine/collider/#enabled","text":"enabled : boolean. Is the collider enabled? A collider that is not enabled will not notify the parent object if a collision occurs. The default value is true , i.e., colliders are enabled by default.","title":"enabled"},{"location":"engine/collider/#visible","text":"visible : boolean. Is the collider visible? This is useful for debugging. The default value is false .","title":"visible"},{"location":"engine/collider/#anchor","text":"anchor : Vector2 object. The anchor of the collider. See also: setAnchor . Available since: Open Surge 0.6.0","title":"anchor"},{"location":"engine/collider/#functions","text":"","title":"Functions"},{"location":"engine/collider/#collideswith","text":"collidesWith(collider) Checks if this collider is colliding with some other collider. Arguments collider : Collider object. The other collider. Returns Returns true if there is a collision (the colliders overlap), or false otherwise.","title":"collidesWith"},{"location":"engine/collider/#contains","text":"contains(point) Checks if the collider contains the given point, given in world coordinates. Arguments point : Vector2 object. The point to be tested. Returns Returns true if the point is contained in the collider, or false otherwise.","title":"contains"},{"location":"engine/collider/#setanchor","text":"setAnchor(x, y) Defines the anchor of the collider to be ( x , y ), where these values are (usually) numbers between 0.0 and 1.0. Imagine a bounding box of the collider. Point (0.5, 0.5) is the default, representing its center. Point (0.0, 0.0) is the top-left and (1,0, 1.0), the bottom-right. The anchor of the collider will be aligned to the hot spot of the sprite of the entity. See also: anchor . Arguments x : number. Usually a value between 0.0 and 1.0. y : number. Usually a value between 0.0 and 1.0. Returns Returns the collider itself. Example // ... using SurgeEngine.Collisions.CollisionBox ; object \"CollisionTestObject\" is \"entity\" { // see that the following collision box // has its anchor on pixel (16, 64) collider = CollisionBox ( 32 , 64 ). setAnchor ( 0.5 , 1.0 ); // ... }","title":"setAnchor"},{"location":"engine/collisionball/","text":"CollisionBall A CollisionBall is a special type of Collider that takes the shape of a ball. In 2D space, this is a circle with a specific radius. All functions and properties of Collider apply to this. Example using SurgeEngine.Actor ; using SurgeEngine.Collisions.CollisionBall ; object \"CollisionDoll\" is \"entity\" { actor = Actor ( \"CollisionDoll\" ); collider = CollisionBall ( 25 ); // radius = 25px state \"main\" { collider . visible = true ; // useful for debugging } fun onCollision ( otherCollider ) { Console . print ( \"A collision has occurred.\" ); } } Factory Collisions.CollisionBall Collisions.CollisionBall(radius) Spawns a new CollisionBall with the specified radius, in pixels. Arguments radius : number. The radius of the CollisionBall. Returns A new CollisionBall with the specified radius. Properties center center : Vector2 , read-only. The center of the CollisionBall, in world space. radius radius : number. The radius of the CollisionBall, in pixels.","title":"CollisionBall"},{"location":"engine/collisionball/#collisionball","text":"A CollisionBall is a special type of Collider that takes the shape of a ball. In 2D space, this is a circle with a specific radius. All functions and properties of Collider apply to this. Example using SurgeEngine.Actor ; using SurgeEngine.Collisions.CollisionBall ; object \"CollisionDoll\" is \"entity\" { actor = Actor ( \"CollisionDoll\" ); collider = CollisionBall ( 25 ); // radius = 25px state \"main\" { collider . visible = true ; // useful for debugging } fun onCollision ( otherCollider ) { Console . print ( \"A collision has occurred.\" ); } }","title":"CollisionBall"},{"location":"engine/collisionball/#factory","text":"","title":"Factory"},{"location":"engine/collisionball/#collisionscollisionball","text":"Collisions.CollisionBall(radius) Spawns a new CollisionBall with the specified radius, in pixels. Arguments radius : number. The radius of the CollisionBall. Returns A new CollisionBall with the specified radius.","title":"Collisions.CollisionBall"},{"location":"engine/collisionball/#properties","text":"","title":"Properties"},{"location":"engine/collisionball/#center","text":"center : Vector2 , read-only. The center of the CollisionBall, in world space.","title":"center"},{"location":"engine/collisionball/#radius","text":"radius : number. The radius of the CollisionBall, in pixels.","title":"radius"},{"location":"engine/collisionbox/","text":"CollisionBox A CollisionBox is a special type of Collider that takes the shape of a box. In 2D space, this is a rectangle with a specific width and height. All functions and properties of Collider apply to this. Example using SurgeEngine.Actor ; using SurgeEngine.Collisions.CollisionBox ; object \"CollisionDoll\" is \"entity\" { actor = Actor ( \"CollisionDoll\" ); collider = CollisionBox ( 32 , 64 ); // width = 32px, height = 64px state \"main\" { collider . visible = true ; // useful for debugging } fun onCollision ( otherCollider ) { Console . print ( \"A collision has occurred.\" ); } } Factory Collisions.CollisionBox Collisions.CollisionBox(width, height) Spawns a new CollisionBox with the specified dimensions, in pixels. Arguments width : number. The width of the CollisionBox. height : number. The height of the CollisionBox. Returns A new CollisionBox with the specified dimensions. Properties width width : number. The width of the CollisionBox, in pixels. height height : number. The height of the CollisionBox, in pixels. center center : Vector2 , read-only. The center of the CollisionBox, in world space. top top : number, read-only. The y-coordinate of the top border of the CollisionBox, in world space. right right : number, read-only. The x-coordinate of the right border of the CollisionBox, in world space. bottom bottom : number, read-only. The y-coordinate of the bottom border of the CollisionBox, in world space. left left : number, read-only. The x-coordinate of the left border of the CollisionBox, in world space.","title":"CollisionBox"},{"location":"engine/collisionbox/#collisionbox","text":"A CollisionBox is a special type of Collider that takes the shape of a box. In 2D space, this is a rectangle with a specific width and height. All functions and properties of Collider apply to this. Example using SurgeEngine.Actor ; using SurgeEngine.Collisions.CollisionBox ; object \"CollisionDoll\" is \"entity\" { actor = Actor ( \"CollisionDoll\" ); collider = CollisionBox ( 32 , 64 ); // width = 32px, height = 64px state \"main\" { collider . visible = true ; // useful for debugging } fun onCollision ( otherCollider ) { Console . print ( \"A collision has occurred.\" ); } }","title":"CollisionBox"},{"location":"engine/collisionbox/#factory","text":"","title":"Factory"},{"location":"engine/collisionbox/#collisionscollisionbox","text":"Collisions.CollisionBox(width, height) Spawns a new CollisionBox with the specified dimensions, in pixels. Arguments width : number. The width of the CollisionBox. height : number. The height of the CollisionBox. Returns A new CollisionBox with the specified dimensions.","title":"Collisions.CollisionBox"},{"location":"engine/collisionbox/#properties","text":"","title":"Properties"},{"location":"engine/collisionbox/#width","text":"width : number. The width of the CollisionBox, in pixels.","title":"width"},{"location":"engine/collisionbox/#height","text":"height : number. The height of the CollisionBox, in pixels.","title":"height"},{"location":"engine/collisionbox/#center","text":"center : Vector2 , read-only. The center of the CollisionBox, in world space.","title":"center"},{"location":"engine/collisionbox/#top","text":"top : number, read-only. The y-coordinate of the top border of the CollisionBox, in world space.","title":"top"},{"location":"engine/collisionbox/#right","text":"right : number, read-only. The x-coordinate of the right border of the CollisionBox, in world space.","title":"right"},{"location":"engine/collisionbox/#bottom","text":"bottom : number, read-only. The y-coordinate of the bottom border of the CollisionBox, in world space.","title":"bottom"},{"location":"engine/collisionbox/#left","text":"left : number, read-only. The x-coordinate of the left border of the CollisionBox, in world space.","title":"left"},{"location":"engine/delayedevent/","text":"DelayedEvent A DelayedEvent is an event that, when triggered, triggers another event after a specified time has passed. Factory Events.DelayedEvent Events.DelayedEvent(event) Spawns a DelayedEvent. Arguments event : event object. The event to be delayed. Returns A new DelayedEvent that, when triggered, will trigger the specified event after a delay. Example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventList ; using SurgeEngine.Events.DelayedEvent ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : EventList ([ FunctionEvent ( \"Print\" ). withArgument ( \"Hello!\" ), DelayedEvent ( FunctionEvent ( \"Print\" ). withArgument ( \"This is...\" ) ). willWait ( 2.0 ), // wait 2 seconds before triggering this DelayedEvent ( FunctionEvent ( \"Print\" ). withArgument ( \"SurgeScript!\" ) ). willWait ( 4.0 ) // wait 4 seconds before triggering this ]) } }); } } Functions willWait willWait(seconds) Set the delay to trigger the event. Arguments seconds : number. The delay, in seconds. Returns The DelayedEvent object. call call() Triggers the event.","title":"DelayedEvent"},{"location":"engine/delayedevent/#delayedevent","text":"A DelayedEvent is an event that, when triggered, triggers another event after a specified time has passed.","title":"DelayedEvent"},{"location":"engine/delayedevent/#factory","text":"","title":"Factory"},{"location":"engine/delayedevent/#eventsdelayedevent","text":"Events.DelayedEvent(event) Spawns a DelayedEvent. Arguments event : event object. The event to be delayed. Returns A new DelayedEvent that, when triggered, will trigger the specified event after a delay. Example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventList ; using SurgeEngine.Events.DelayedEvent ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : EventList ([ FunctionEvent ( \"Print\" ). withArgument ( \"Hello!\" ), DelayedEvent ( FunctionEvent ( \"Print\" ). withArgument ( \"This is...\" ) ). willWait ( 2.0 ), // wait 2 seconds before triggering this DelayedEvent ( FunctionEvent ( \"Print\" ). withArgument ( \"SurgeScript!\" ) ). willWait ( 4.0 ) // wait 4 seconds before triggering this ]) } }); } }","title":"Events.DelayedEvent"},{"location":"engine/delayedevent/#functions","text":"","title":"Functions"},{"location":"engine/delayedevent/#willwait","text":"willWait(seconds) Set the delay to trigger the event. Arguments seconds : number. The delay, in seconds. Returns The DelayedEvent object.","title":"willWait"},{"location":"engine/delayedevent/#call","text":"call() Triggers the event.","title":"call"},{"location":"engine/directional_movement/","text":"Directional Movement The Directional Movement behavior makes the associated entity perform a directional movement on the 2D plane. It features: A direction vector that specifies the direction of the movement A movement speed, a scalar value given in pixels per second You may control the direction of the movement using the direction vector or an angle given in degrees. Additionally, you may control the speed of the movement simply by changing its value. Directional Movement is very versatile. You can use it to implement many things: different types of baddies, flying objects, racing cars viewed from a top-down view, simple projectiles, and much more. Example // // The example below shows how to make an entity move to the // right of the screen at a rate of 60 pixels per second // using SurgeEngine.Actor ; using SurgeEngine.Vector2 ; using SurgeEngine.Behaviors.DirectionalMovement ; object \"Simple Ball\" is \"entity\" { actor = Actor ( \"Simple Ball\" ); movement = DirectionalMovement (); state \"main\" { movement . direction = Vector2 . right ; movement . speed = 60 ; } } Factory Behaviors.DirectionalMovement DirectionalMovement() Spawns a DirectionalMovement. Returns A DirectionalMovement object. Properties speed speed : number. The speed of the movement, in pixels per second. direction direction : Vector2 object. The direction of the movement. angle angle : number. The counterclockwise angle of the direction vector, in degrees. 0 means right, 90 means up, etc.","title":"DirectionalMovement"},{"location":"engine/directional_movement/#directional-movement","text":"The Directional Movement behavior makes the associated entity perform a directional movement on the 2D plane. It features: A direction vector that specifies the direction of the movement A movement speed, a scalar value given in pixels per second You may control the direction of the movement using the direction vector or an angle given in degrees. Additionally, you may control the speed of the movement simply by changing its value. Directional Movement is very versatile. You can use it to implement many things: different types of baddies, flying objects, racing cars viewed from a top-down view, simple projectiles, and much more. Example // // The example below shows how to make an entity move to the // right of the screen at a rate of 60 pixels per second // using SurgeEngine.Actor ; using SurgeEngine.Vector2 ; using SurgeEngine.Behaviors.DirectionalMovement ; object \"Simple Ball\" is \"entity\" { actor = Actor ( \"Simple Ball\" ); movement = DirectionalMovement (); state \"main\" { movement . direction = Vector2 . right ; movement . speed = 60 ; } }","title":"Directional Movement"},{"location":"engine/directional_movement/#factory","text":"","title":"Factory"},{"location":"engine/directional_movement/#behaviorsdirectionalmovement","text":"DirectionalMovement() Spawns a DirectionalMovement. Returns A DirectionalMovement object.","title":"Behaviors.DirectionalMovement"},{"location":"engine/directional_movement/#properties","text":"","title":"Properties"},{"location":"engine/directional_movement/#speed","text":"speed : number. The speed of the movement, in pixels per second.","title":"speed"},{"location":"engine/directional_movement/#direction","text":"direction : Vector2 object. The direction of the movement.","title":"direction"},{"location":"engine/directional_movement/#angle","text":"angle : number. The counterclockwise angle of the direction vector, in degrees. 0 means right, 90 means up, etc.","title":"angle"},{"location":"engine/enemy/","text":"Enemy The Enemy behavior makes the associated entity behave like an enemy. It will hit the player if touched, unless the player is attacking (jumping, rolling, etc.) In this case the enemy will be destroyed with an explosion, giving the player a certain score. Although the Enemy object generates the described behavior, it is not a concrete enemy itself. You may use it to script your own baddies. Example // // HOW TO SCRIPT A BADDIE: // // 0. Make sure you have the graphics and the sprite file (.spr) ready, // before you begin with SurgeScript // 1. Your object should be tagged (at least): \"entity\", \"enemy\" // 2. Spawn an Actor for the graphics and an Enemy object for the behavior. // using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.Platformer ; object \"My Baddie\" is \"entity\" , \"enemy\" { actor = Actor ( \"My Baddie\" ); // handles the graphics enemy = Enemy (); // handles the behavior platformer = Platformer (). walk (); // make it walk state \"main\" { enemy . score = 100 ; } } Optionally, you may define functions onEnemyAttack(player) and onEnemyDestroy(player) in your entity if you want to catch the events: the enemy has attacked a player and the enemy has been destroyed by the player, respectively. Factory Behaviors.Enemy Enemy() Spawns an Enemy behavior. Returns An Enemy behavior object. Properties score score : number. The score given to the player when the enemy is defeated. invincible invincible : boolean. Is the enemy invincible? An invincible enemy hits the player even when jumping, rolling, etc. - except if the player is also invincible. Defaults to false . collider collider : Collider object, read-only. A collider associated with the enemy. Functions kill kill(player) Destroys the enemy with an explosion, giving score to player . Available since: Open Surge 0.5.1. See the note below. Arguments player : Player object. The player who defeats the enemy. Note: in versions prior to 0.5.1, this function was called getDestroyed . setBounds setBounds(left, top, right, bottom) Set the boundaries of the collider. All coordinates, given in pixels, are relative to the hot spot of the entity. These boundaries are computed automatically, but you may use this function if you need to adjust them. Arguments left : number. Given in pixels. top : number. Given in pixels. right : number. Given in pixels. down : number. Given in pixels. Returns Returns the Enemy behavior itself.","title":"Enemy"},{"location":"engine/enemy/#enemy","text":"The Enemy behavior makes the associated entity behave like an enemy. It will hit the player if touched, unless the player is attacking (jumping, rolling, etc.) In this case the enemy will be destroyed with an explosion, giving the player a certain score. Although the Enemy object generates the described behavior, it is not a concrete enemy itself. You may use it to script your own baddies. Example // // HOW TO SCRIPT A BADDIE: // // 0. Make sure you have the graphics and the sprite file (.spr) ready, // before you begin with SurgeScript // 1. Your object should be tagged (at least): \"entity\", \"enemy\" // 2. Spawn an Actor for the graphics and an Enemy object for the behavior. // using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.Platformer ; object \"My Baddie\" is \"entity\" , \"enemy\" { actor = Actor ( \"My Baddie\" ); // handles the graphics enemy = Enemy (); // handles the behavior platformer = Platformer (). walk (); // make it walk state \"main\" { enemy . score = 100 ; } } Optionally, you may define functions onEnemyAttack(player) and onEnemyDestroy(player) in your entity if you want to catch the events: the enemy has attacked a player and the enemy has been destroyed by the player, respectively.","title":"Enemy"},{"location":"engine/enemy/#factory","text":"","title":"Factory"},{"location":"engine/enemy/#behaviorsenemy","text":"Enemy() Spawns an Enemy behavior. Returns An Enemy behavior object.","title":"Behaviors.Enemy"},{"location":"engine/enemy/#properties","text":"","title":"Properties"},{"location":"engine/enemy/#score","text":"score : number. The score given to the player when the enemy is defeated.","title":"score"},{"location":"engine/enemy/#invincible","text":"invincible : boolean. Is the enemy invincible? An invincible enemy hits the player even when jumping, rolling, etc. - except if the player is also invincible. Defaults to false .","title":"invincible"},{"location":"engine/enemy/#collider","text":"collider : Collider object, read-only. A collider associated with the enemy.","title":"collider"},{"location":"engine/enemy/#functions","text":"","title":"Functions"},{"location":"engine/enemy/#kill","text":"kill(player) Destroys the enemy with an explosion, giving score to player . Available since: Open Surge 0.5.1. See the note below. Arguments player : Player object. The player who defeats the enemy. Note: in versions prior to 0.5.1, this function was called getDestroyed .","title":"kill"},{"location":"engine/enemy/#setbounds","text":"setBounds(left, top, right, bottom) Set the boundaries of the collider. All coordinates, given in pixels, are relative to the hot spot of the entity. These boundaries are computed automatically, but you may use this function if you need to adjust them. Arguments left : number. Given in pixels. top : number. Given in pixels. right : number. Given in pixels. down : number. Given in pixels. Returns Returns the Enemy behavior itself.","title":"setBounds"},{"location":"engine/entity/","text":"Entity An entity is an object that generally is present in the virtual world. Examples include: a pickup item, a gimmick, a non-playable-character, and so on. Entites have special treatment: Entities can have components associated to it. They can be fully customized. By default, they are automatically disabled and moved back to their initial position in the world if they get too far off camera. Behavior can be changed by adding special tags them. The engine will automatically call special functions if you define them. Definition A SurgeScript object is considered to be an entity if it meets all of the following conditions: the object is tagged \"entity\" the object is a direct child of Level or a direct child of another entity Objects that are direct children of entities but that are not tagged \"entity\" are considered to be components . Components are meant to modify the entities in some way. Components may not have any entities as descendants. For example: a child of a component is not considered to be an entity, even if it's tagged \"entity\". Level setup objects and player companion objects are special cases. They are always considered to be entities, regardless if they are tagged \"entity\" or not, for backwards compatibility purposes. Tip During level design, entities may be placed in world space using the editor palette. The icon of the entity will be the first animation (animation 0) of the sprite that has the name of the entity. Tags entity Mark the object as an entity. // In the example below, entity \"My Explosion\" has an Actor // component that gives it visible form: a sprite. using SurgeEngine.Actor ; object \"My Explosion\" is \"entity\" , \"private\" , \"disposable\" { actor = Actor ( \"My Explosion\" ); state \"main\" { if ( actor . animation . finished ) destroy (); } } private Private entities cannot be spawned via the level editor - they will be hidden. awake Don't disable the object nor move it back to its initial position if it gets too far off camera. Performance tip The engine optimizes entities that are not awake by \"putting them to sleep\" whenever they are too far off camera. Take advantage of this optimization by not making your entities awake unless you need to. disposable The engine will automatically destroy the object if it gets too far off camera. detached The object will not follow the camera. It will be rendered in screen space. Effectively detached entities If a non-detached entity is a descendant of a detached entity, the former is effetively detached . Effectively detached entites are rendered just like detached entities. (since 0.6.1) Functions lateUpdate lateUpdate() If lateUpdate() is implemented in your entity, it will be called after all other objects have been updated. This handy function helps order script execution. For example: a routine that controls the Camera should be implemented in lateUpdate() , since it's guaranteed to be executed after other entities have been updated. Available since: Open Surge 0.6.1 Example using SurgeEngine.Camera ; using SurgeEngine.Player ; object \"My Simple Camera\" is \"awake\" , \"entity\" { fun lateUpdate () { player = Player . active ; Camera . position = player . transform . position ; } } onReset onReset() If an entity that is not awake nor detached gets too far off camera, it will be automatically disabled and moved back to its initial position. Whenever that happens, the engine will call this function if it's available in your entity. You may use this function to reset the entity back to its initial state. Note Entities tagged \"awake\" or \"detached\" are not affected by onReset() . Example using SurgeEngine.UI.Text ; // The object below is a simple counter that gets // reseted whenever it gets too far off camera. object \"My Test Counter\" is \"entity\" { label = Text ( \"default\" ); counter = 0 ; state \"main\" { Console . print ( \"Starting the counter...\" ); state = \"wait\" ; } state \"wait\" { label . text = counter ; if ( timeout ( 1.0 )) state = \"increment\" ; } state \"increment\" { counter ++; state = \"wait\" ; } // Without implementing function onReset() below, // the counter would retain its state. fun onReset () { counter = 0 ; state = \"main\" ; } } onLeaveEditor onLeaveEditor() If declared, function onLeaveEditor() will be called whenever the player leaves the level editor and returns to the game. This may be useful to reconfigure your objects.","title":"Entity"},{"location":"engine/entity/#entity","text":"An entity is an object that generally is present in the virtual world. Examples include: a pickup item, a gimmick, a non-playable-character, and so on. Entites have special treatment: Entities can have components associated to it. They can be fully customized. By default, they are automatically disabled and moved back to their initial position in the world if they get too far off camera. Behavior can be changed by adding special tags them. The engine will automatically call special functions if you define them. Definition A SurgeScript object is considered to be an entity if it meets all of the following conditions: the object is tagged \"entity\" the object is a direct child of Level or a direct child of another entity Objects that are direct children of entities but that are not tagged \"entity\" are considered to be components . Components are meant to modify the entities in some way. Components may not have any entities as descendants. For example: a child of a component is not considered to be an entity, even if it's tagged \"entity\". Level setup objects and player companion objects are special cases. They are always considered to be entities, regardless if they are tagged \"entity\" or not, for backwards compatibility purposes. Tip During level design, entities may be placed in world space using the editor palette. The icon of the entity will be the first animation (animation 0) of the sprite that has the name of the entity.","title":"Entity"},{"location":"engine/entity/#tags","text":"","title":"Tags"},{"location":"engine/entity/#entity_1","text":"Mark the object as an entity. // In the example below, entity \"My Explosion\" has an Actor // component that gives it visible form: a sprite. using SurgeEngine.Actor ; object \"My Explosion\" is \"entity\" , \"private\" , \"disposable\" { actor = Actor ( \"My Explosion\" ); state \"main\" { if ( actor . animation . finished ) destroy (); } }","title":"entity"},{"location":"engine/entity/#private","text":"Private entities cannot be spawned via the level editor - they will be hidden.","title":"private"},{"location":"engine/entity/#awake","text":"Don't disable the object nor move it back to its initial position if it gets too far off camera. Performance tip The engine optimizes entities that are not awake by \"putting them to sleep\" whenever they are too far off camera. Take advantage of this optimization by not making your entities awake unless you need to.","title":"awake"},{"location":"engine/entity/#disposable","text":"The engine will automatically destroy the object if it gets too far off camera.","title":"disposable"},{"location":"engine/entity/#detached","text":"The object will not follow the camera. It will be rendered in screen space. Effectively detached entities If a non-detached entity is a descendant of a detached entity, the former is effetively detached . Effectively detached entites are rendered just like detached entities. (since 0.6.1)","title":"detached"},{"location":"engine/entity/#functions","text":"","title":"Functions"},{"location":"engine/entity/#lateupdate","text":"lateUpdate() If lateUpdate() is implemented in your entity, it will be called after all other objects have been updated. This handy function helps order script execution. For example: a routine that controls the Camera should be implemented in lateUpdate() , since it's guaranteed to be executed after other entities have been updated. Available since: Open Surge 0.6.1 Example using SurgeEngine.Camera ; using SurgeEngine.Player ; object \"My Simple Camera\" is \"awake\" , \"entity\" { fun lateUpdate () { player = Player . active ; Camera . position = player . transform . position ; } }","title":"lateUpdate"},{"location":"engine/entity/#onreset","text":"onReset() If an entity that is not awake nor detached gets too far off camera, it will be automatically disabled and moved back to its initial position. Whenever that happens, the engine will call this function if it's available in your entity. You may use this function to reset the entity back to its initial state. Note Entities tagged \"awake\" or \"detached\" are not affected by onReset() . Example using SurgeEngine.UI.Text ; // The object below is a simple counter that gets // reseted whenever it gets too far off camera. object \"My Test Counter\" is \"entity\" { label = Text ( \"default\" ); counter = 0 ; state \"main\" { Console . print ( \"Starting the counter...\" ); state = \"wait\" ; } state \"wait\" { label . text = counter ; if ( timeout ( 1.0 )) state = \"increment\" ; } state \"increment\" { counter ++; state = \"wait\" ; } // Without implementing function onReset() below, // the counter would retain its state. fun onReset () { counter = 0 ; state = \"main\" ; } }","title":"onReset"},{"location":"engine/entity/#onleaveeditor","text":"onLeaveEditor() If declared, function onLeaveEditor() will be called whenever the player leaves the level editor and returns to the game. This may be useful to reconfigure your objects.","title":"onLeaveEditor"},{"location":"engine/entityevent/","text":"EntityEvent An EntityEvent is an event that calls a function of an entity when triggered. Factory Events.EntityEvent Events.EntityEvent Spawns an EntityEvent. Arguments entityID : string. The ID of an entity. Returns A new EntityEvent linked to the specified entity. Example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EntityEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : EntityEvent ( \"aeb587eed1057a5e\" ). willCall ( \"open\" ) } }); } } Functions willCall willCall(functionName) Specifies the name of the function that will be called. Arguments functionName : string. The name of the function that will be called when the event is triggered. Returns The EntityEvent object. withArgument withArgument(data) Adds an argument to the EntityEvent. Arguments added to the EntityEvent will be passed to the entity when the event is triggered - in the order they have been added. To add multiple arguments, call this function multiple times. Arguments data : any. The argument to be added. Returns The EntityEvent object. call call() Triggers the event.","title":"EntityEvent"},{"location":"engine/entityevent/#entityevent","text":"An EntityEvent is an event that calls a function of an entity when triggered.","title":"EntityEvent"},{"location":"engine/entityevent/#factory","text":"","title":"Factory"},{"location":"engine/entityevent/#eventsentityevent","text":"Events.EntityEvent Spawns an EntityEvent. Arguments entityID : string. The ID of an entity. Returns A new EntityEvent linked to the specified entity. Example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EntityEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : EntityEvent ( \"aeb587eed1057a5e\" ). willCall ( \"open\" ) } }); } }","title":"Events.EntityEvent"},{"location":"engine/entityevent/#functions","text":"","title":"Functions"},{"location":"engine/entityevent/#willcall","text":"willCall(functionName) Specifies the name of the function that will be called. Arguments functionName : string. The name of the function that will be called when the event is triggered. Returns The EntityEvent object.","title":"willCall"},{"location":"engine/entityevent/#withargument","text":"withArgument(data) Adds an argument to the EntityEvent. Arguments added to the EntityEvent will be passed to the entity when the event is triggered - in the order they have been added. To add multiple arguments, call this function multiple times. Arguments data : any. The argument to be added. Returns The EntityEvent object.","title":"withArgument"},{"location":"engine/entityevent/#call","text":"call() Triggers the event.","title":"call"},{"location":"engine/event/","text":"Event An event is a function object with zero parameters and no return value that is tagged \"event\" . Events are used to run code when triggered. Events let you seamlessly connect entities and write cause and effect relationships. Suppose you have an on/off switch in a level. Whenever that switch is pressed by the player, you want something to happen: raise the water level, open a door, make it rain, teleport the player, and so on. Events are important because they let you decouple the source of the happening (the pressing of the switch) from the results that are experienced (e.g., the raising of the water). Events let you reuse your entities in multiple ways and for multiple purposes. You may design an entity and make it trigger an event, but you do not need to specify in advance what the event actually is. Rather, the concrete event (what must happen) will be configured in your level setup . There are multiple types of events. In practice, you'll use specialized events such as EntityEvent and FunctionEvent when configuring your entities. Event is an empty event that does nothing when triggered, but it should be used when designing your entities, as in the example below. Example // ----------------------------------------------------------------------------- // Using Events // // Note that cause and effect are split into different scripts! // ----------------------------------------------------------------------------- // This script contains an object that will trigger an event whenever a certain // button is pressed (e.g., the jump button). using SurgeEngine.Player ; using SurgeEngine.Events.Event ; object \"Button Detector\" is \"awake\" , \"entity\" { public onButtonPress = Event (); public button = \"fire1\" ; state \"main\" { input = Player . active . input ; if ( input . buttonPressed ( button )) onButtonPress (); } } // ----------------------------------------------------------------------------- // The code below is a different script containing a level setup object. // Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Button Detector\" : { \"button\" : \"fire1\" , // \"fire1\" is the jump button \"onButtonPress\" : FunctionEvent ( \"Print\" ). withArgument ( \"You pressed the button!\" ) } }); } } Factory Events.Event Events.Event() Spawns an empty Event. Returns A new Event. Functions call call() Triggers the event. All event types implement this function. It takes no arguments and it returns no value other than null .","title":"Event"},{"location":"engine/event/#event","text":"An event is a function object with zero parameters and no return value that is tagged \"event\" . Events are used to run code when triggered. Events let you seamlessly connect entities and write cause and effect relationships. Suppose you have an on/off switch in a level. Whenever that switch is pressed by the player, you want something to happen: raise the water level, open a door, make it rain, teleport the player, and so on. Events are important because they let you decouple the source of the happening (the pressing of the switch) from the results that are experienced (e.g., the raising of the water). Events let you reuse your entities in multiple ways and for multiple purposes. You may design an entity and make it trigger an event, but you do not need to specify in advance what the event actually is. Rather, the concrete event (what must happen) will be configured in your level setup . There are multiple types of events. In practice, you'll use specialized events such as EntityEvent and FunctionEvent when configuring your entities. Event is an empty event that does nothing when triggered, but it should be used when designing your entities, as in the example below. Example // ----------------------------------------------------------------------------- // Using Events // // Note that cause and effect are split into different scripts! // ----------------------------------------------------------------------------- // This script contains an object that will trigger an event whenever a certain // button is pressed (e.g., the jump button). using SurgeEngine.Player ; using SurgeEngine.Events.Event ; object \"Button Detector\" is \"awake\" , \"entity\" { public onButtonPress = Event (); public button = \"fire1\" ; state \"main\" { input = Player . active . input ; if ( input . buttonPressed ( button )) onButtonPress (); } } // ----------------------------------------------------------------------------- // The code below is a different script containing a level setup object. // Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Button Detector\" : { \"button\" : \"fire1\" , // \"fire1\" is the jump button \"onButtonPress\" : FunctionEvent ( \"Print\" ). withArgument ( \"You pressed the button!\" ) } }); } }","title":"Event"},{"location":"engine/event/#factory","text":"","title":"Factory"},{"location":"engine/event/#eventsevent","text":"Events.Event() Spawns an empty Event. Returns A new Event.","title":"Events.Event"},{"location":"engine/event/#functions","text":"","title":"Functions"},{"location":"engine/event/#call","text":"call() Triggers the event. All event types implement this function. It takes no arguments and it returns no value other than null .","title":"call"},{"location":"engine/eventchain/","text":"EventChain An EventChain is an event that triggers other events sequentially, as in a chain of events. Factory Events.EventChain Events.EventChain(chain) Spawns an EventChain. Arguments chain : Array object. A list containing zero or more events. Returns A new EventChain that triggers the specified events, one at a time. The first time the EventChain is triggered, the first event of the chain will be triggered. The second time the EventChain is triggered, the second event of the chain will be triggered, and so on. Note: if the EventChain ever triggers its last event, from that moment onwards it will always trigger its last event (unless you make it loop). Example // EventChain example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventChain ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Switch\" : { \"sticky\" : false , \"onActivate\" : EventChain ([ FunctionEvent ( \"Print\" ). withArgument ( \"First time\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Second time\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Third time\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Enough!\" ) ]) } }); } } Functions willLoop willLoop() Make the EventChain loop. When the last event of the chain is triggered, the next event to be triggered will be the first one. Returns The EventChain object. Example // Triggering Alternating Events // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventChain ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup - Alternating Events\" { fun constructor () { Level . setup ({ \"Switch\" : { \"sticky\" : false , \"onActivate\" : EventChain ([ FunctionEvent ( \"Print\" ). withArgument ( \"Triggered Event A\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Triggered Event B\" ) ]). willLoop () } }); } } call call() Triggers the event.","title":"EventChain"},{"location":"engine/eventchain/#eventchain","text":"An EventChain is an event that triggers other events sequentially, as in a chain of events.","title":"EventChain"},{"location":"engine/eventchain/#factory","text":"","title":"Factory"},{"location":"engine/eventchain/#eventseventchain","text":"Events.EventChain(chain) Spawns an EventChain. Arguments chain : Array object. A list containing zero or more events. Returns A new EventChain that triggers the specified events, one at a time. The first time the EventChain is triggered, the first event of the chain will be triggered. The second time the EventChain is triggered, the second event of the chain will be triggered, and so on. Note: if the EventChain ever triggers its last event, from that moment onwards it will always trigger its last event (unless you make it loop). Example // EventChain example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventChain ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Switch\" : { \"sticky\" : false , \"onActivate\" : EventChain ([ FunctionEvent ( \"Print\" ). withArgument ( \"First time\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Second time\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Third time\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Enough!\" ) ]) } }); } }","title":"Events.EventChain"},{"location":"engine/eventchain/#functions","text":"","title":"Functions"},{"location":"engine/eventchain/#willloop","text":"willLoop() Make the EventChain loop. When the last event of the chain is triggered, the next event to be triggered will be the first one. Returns The EventChain object. Example // Triggering Alternating Events // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventChain ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup - Alternating Events\" { fun constructor () { Level . setup ({ \"Switch\" : { \"sticky\" : false , \"onActivate\" : EventChain ([ FunctionEvent ( \"Print\" ). withArgument ( \"Triggered Event A\" ), FunctionEvent ( \"Print\" ). withArgument ( \"Triggered Event B\" ) ]). willLoop () } }); } }","title":"willLoop"},{"location":"engine/eventchain/#call","text":"call() Triggers the event.","title":"call"},{"location":"engine/eventlist/","text":"EventList An EventList is an event that triggers multiple events when triggered. Factory Events.EventList Events.EventList(list) Spawns an EventList. Arguments list : Array object. A list containing zero or more events. Returns A new EventList that triggers the specified events at once, in the order they have been listed. Example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventList ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : EventList ([ FunctionEvent ( \"Print\" ). withArgument ( \"We're triggering\" ), FunctionEvent ( \"Print\" ). withArgument ( \"multiple events\" ), FunctionEvent ( \"Print\" ). withArgument ( \"at the same time!\" ) ]) } }); } } Functions call call() Triggers the event.","title":"EventList"},{"location":"engine/eventlist/#eventlist","text":"An EventList is an event that triggers multiple events when triggered.","title":"EventList"},{"location":"engine/eventlist/#factory","text":"","title":"Factory"},{"location":"engine/eventlist/#eventseventlist","text":"Events.EventList(list) Spawns an EventList. Arguments list : Array object. A list containing zero or more events. Returns A new EventList that triggers the specified events at once, in the order they have been listed. Example // This is a level setup object. Make sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.EventList ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : EventList ([ FunctionEvent ( \"Print\" ). withArgument ( \"We're triggering\" ), FunctionEvent ( \"Print\" ). withArgument ( \"multiple events\" ), FunctionEvent ( \"Print\" ). withArgument ( \"at the same time!\" ) ]) } }); } }","title":"Events.EventList"},{"location":"engine/eventlist/#functions","text":"","title":"Functions"},{"location":"engine/eventlist/#call","text":"call() Triggers the event.","title":"call"},{"location":"engine/functionevent/","text":"FunctionEvent A FunctionEvent is an event that calls a function object when triggered. Factory Events.FunctionEvent Events.FunctionEvent(objectName) Spawns a FunctionEvent. Arguments objectName : string. The name of a function object. Returns A new FunctionEvent that, when triggered, calls the specified function object. Example // This is a level setup object. Make // sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : FunctionEvent ( \"Give 1up\" ) } }); } } // ----------------------------------------- // This is a function object that // gives the player one extra life. using SurgeEngine.Player ; using SurgeEngine.Audio.Music ; object \"Give 1up\" { jingle = Music ( \"samples/1up.ogg\" ); fun call () { Player . active . lives += 1 ; jingle . play (); } } Functions withArgument withArgument(data) Adds an argument to the FunctionEvent. Arguments added to the FunctionEvent will be passed to the function object when the event is triggered - in the order they have been added. To add multiple arguments, call this function multiple times. Arguments data : any. The argument to be added. Returns The FunctionEvent object. call call() Triggers the event.","title":"FunctionEvent"},{"location":"engine/functionevent/#functionevent","text":"A FunctionEvent is an event that calls a function object when triggered.","title":"FunctionEvent"},{"location":"engine/functionevent/#factory","text":"","title":"Factory"},{"location":"engine/functionevent/#eventsfunctionevent","text":"Events.FunctionEvent(objectName) Spawns a FunctionEvent. Arguments objectName : string. The name of a function object. Returns A new FunctionEvent that, when triggered, calls the specified function object. Example // This is a level setup object. Make // sure to link it in your .lev file! using SurgeEngine.Level ; using SurgeEngine.Events.FunctionEvent ; object \"My Level Setup\" { fun constructor () { Level . setup ({ \"Event Trigger 1\" : { \"onTrigger\" : FunctionEvent ( \"Give 1up\" ) } }); } } // ----------------------------------------- // This is a function object that // gives the player one extra life. using SurgeEngine.Player ; using SurgeEngine.Audio.Music ; object \"Give 1up\" { jingle = Music ( \"samples/1up.ogg\" ); fun call () { Player . active . lives += 1 ; jingle . play (); } }","title":"Events.FunctionEvent"},{"location":"engine/functionevent/#functions","text":"","title":"Functions"},{"location":"engine/functionevent/#withargument","text":"withArgument(data) Adds an argument to the FunctionEvent. Arguments added to the FunctionEvent will be passed to the function object when the event is triggered - in the order they have been added. To add multiple arguments, call this function multiple times. Arguments data : any. The argument to be added. Returns The FunctionEvent object.","title":"withArgument"},{"location":"engine/functionevent/#call","text":"call() Triggers the event.","title":"call"},{"location":"engine/game/","text":"Game Game settings. These are specified in surge.cfg , a file located at the root folder of the game. Available since: Open Surge 0.6.1 Properties title title : string, read-only. The title of the game that is running on the engine. If unspecified, an empty string is returned. version version : string, read-only. The version of the game that is running on the engine. If unspecified, an empty string is returned. Do not confuse it with SurgeEngine.version .","title":"Game"},{"location":"engine/game/#game","text":"Game settings. These are specified in surge.cfg , a file located at the root folder of the game. Available since: Open Surge 0.6.1","title":"Game"},{"location":"engine/game/#properties","text":"","title":"Properties"},{"location":"engine/game/#title","text":"title : string, read-only. The title of the game that is running on the engine. If unspecified, an empty string is returned.","title":"title"},{"location":"engine/game/#version","text":"version : string, read-only. The version of the game that is running on the engine. If unspecified, an empty string is returned. Do not confuse it with SurgeEngine.version .","title":"version"},{"location":"engine/input/","text":"Input The Input object is used to read input from the user. Example using SurgeEngine.Player ; object \"Application\" { player = Player . active ; state \"main\" { if ( player . input . buttonDown ( \"right\" )) Console . print ( \"User is holding right\" ); } } Factory Input Input(inputMap) Spawns a new Input component with the given input map. Note: to read input from a specific character, prefer using Player.input instead. Arguments inputMap : string. The name of the input map. If set to null , a default input map will be used. Returns An Input component. Example using SurgeEngine.Player ; using SurgeEngine.Input ; object \"Application\" { input = Player . active . input ; // this form is preferred (used in most cases) //input = Input(\"custom input map\"); // unless you need to read a custom input map state \"main\" { if ( input . buttonDown ( \"right\" )) Console . print ( \"User is holding right\" ); } } Properties enabled enabled : boolean. Whether the input object is enabled or not. A disabled object does not receive user input. The default value of this property is true . Functions buttonDown buttonDown(buttonName) Checks if a button of the input map is currently being held down. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . Returns Returns true if the specified button is being held down. buttonPressed buttonPressed(buttonName) Checks if a button has just been pressed. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . Returns Returns true if the specified button has just been pressed. buttonReleased buttonReleased(buttonName) Checks if a button has just been released. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . Returns Returns true if the specified button has just been released. simulateButton simulateButton(buttonName, down) Changes the input object so that buttonName will be identified as being held down, or not being held down, in the current frame. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . down : boolean. Should the button be considered as being held down? remap remap(inputMap) Changes the input map. Available since: Open Surge 0.6.1 Arguments inputMap : string. The name of the input map. Returns Returns true on success, or false otherwise.","title":"Input"},{"location":"engine/input/#input","text":"The Input object is used to read input from the user. Example using SurgeEngine.Player ; object \"Application\" { player = Player . active ; state \"main\" { if ( player . input . buttonDown ( \"right\" )) Console . print ( \"User is holding right\" ); } }","title":"Input"},{"location":"engine/input/#factory","text":"","title":"Factory"},{"location":"engine/input/#input_1","text":"Input(inputMap) Spawns a new Input component with the given input map. Note: to read input from a specific character, prefer using Player.input instead. Arguments inputMap : string. The name of the input map. If set to null , a default input map will be used. Returns An Input component. Example using SurgeEngine.Player ; using SurgeEngine.Input ; object \"Application\" { input = Player . active . input ; // this form is preferred (used in most cases) //input = Input(\"custom input map\"); // unless you need to read a custom input map state \"main\" { if ( input . buttonDown ( \"right\" )) Console . print ( \"User is holding right\" ); } }","title":"Input"},{"location":"engine/input/#properties","text":"","title":"Properties"},{"location":"engine/input/#enabled","text":"enabled : boolean. Whether the input object is enabled or not. A disabled object does not receive user input. The default value of this property is true .","title":"enabled"},{"location":"engine/input/#functions","text":"","title":"Functions"},{"location":"engine/input/#buttondown","text":"buttonDown(buttonName) Checks if a button of the input map is currently being held down. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . Returns Returns true if the specified button is being held down.","title":"buttonDown"},{"location":"engine/input/#buttonpressed","text":"buttonPressed(buttonName) Checks if a button has just been pressed. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . Returns Returns true if the specified button has just been pressed.","title":"buttonPressed"},{"location":"engine/input/#buttonreleased","text":"buttonReleased(buttonName) Checks if a button has just been released. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . Returns Returns true if the specified button has just been released.","title":"buttonReleased"},{"location":"engine/input/#simulatebutton","text":"simulateButton(buttonName, down) Changes the input object so that buttonName will be identified as being held down, or not being held down, in the current frame. Arguments buttonName : string. One of the following: \"up\", \"down\", \"left\", \"right\", \"fire1\", \"fire2\", ..., \"fire8\" . down : boolean. Should the button be considered as being held down?","title":"simulateButton"},{"location":"engine/input/#remap","text":"remap(inputMap) Changes the input map. Available since: Open Surge 0.6.1 Arguments inputMap : string. The name of the input map. Returns Returns true on success, or false otherwise.","title":"remap"},{"location":"engine/lang/","text":"Lang Lang is a SurgeEngine element used to read translation-specific strings, as defined in the language files (.lng). Example using SurgeEngine.Lang ; // Display the current language object \"Application\" { state \"main\" { currentLanguage = Lang [ \"LANG_LANGUAGE\" ]; Console . print ( \"The current language is \" + currentLanguage ); state = \"done\" ; } state \"done\" { } } Functions get get(key) Gets the value of the specified key. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments key : string. The key must always be a string. Returns The translation string associated with the specified key.","title":"Lang"},{"location":"engine/lang/#lang","text":"Lang is a SurgeEngine element used to read translation-specific strings, as defined in the language files (.lng). Example using SurgeEngine.Lang ; // Display the current language object \"Application\" { state \"main\" { currentLanguage = Lang [ \"LANG_LANGUAGE\" ]; Console . print ( \"The current language is \" + currentLanguage ); state = \"done\" ; } state \"done\" { } }","title":"Lang"},{"location":"engine/lang/#functions","text":"","title":"Functions"},{"location":"engine/lang/#get","text":"get(key) Gets the value of the specified key. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments key : string. The key must always be a string. Returns The translation string associated with the specified key.","title":"get"},{"location":"engine/level/","text":"Level Level routines. A level is a scene in the game, stored as a .lev file in the levels/ folder. Whenever you spawn an object in SurgeScript, you must keep a reference to it, otherwise it will be automatically deleted by the Garbage Collector . Sometimes you want to spawn entities in your level, but keeping references to all of them is inconvenient. In this case, you can spawn them as children of the Level object . It will keep the references for you, and thus they won't be garbage collected. Example using SurgeEngine.Actor ; using SurgeEngine.Level ; using SurgeEngine.Vector2 ; object \"Application\" { state \"main\" { createExplosionAt ( 100 , 200 ); state = \"wait\" ; } state \"wait\" { if ( timeout ( 1.0 )) state = \"main\" ; } fun createExplosionAt ( x , y ) { position = Vector2 ( x , y ); return Level . spawnEntity ( \"MyExplosion\" , position ); // no need to keep references } } object \"MyExplosion\" is \"entity\" , \"disposable\" , \"private\" { actor = Actor ( \"MyExplosion\" ); state \"main\" { if ( actor . animation . finished ) destroy () } } Properties name name : string, read-only. The name of the level. Example using SurgeEngine.Level ; // Will display the name of the level object \"Application\" { state \"main\" { Console . print ( Level . name ); state = \"done\" ; } state \"done\" { } } act act : number. The act number (1, 2, 3...) of the current level. Note: this property is writable since Open Surge 0.6.1. cleared cleared : boolean, read-only. Checks if the current level has been cleared by the player. If this is true , a level cleared animation should be played. Although the engine provides a default animation, you may use this property to design your own. See also: clear . file file : string, read-only. The relative path of the .lev file of the current level. version version : string, read-only. The version of the level, defined in the .lev file. author author : string, read-only. The author of the level, defined in the .lev file. license license : string, read-only. The license of the level, defined in the .lev file. music music : Music object, read-only. The music of the level. bgtheme bgtheme : string, read-only. The path to the original background file (.bg), as declared in the .lev file. background background : string. The path to the background file (.bg) currently in use. Use this property to change the background of the level. waterlevel waterlevel : number. The y-coordinate, in world space, of the level water. Pixels not above this value are underwater. spawnpoint spawnpoint : Vector2 object. The position where the player is placed when the level starts. gravity gravity : number, read-only. The acceleration of gravity, measured in pixels per second squared. time time : number. Elapsed time in the level, given in seconds. The level time will be frozen if the cleared flag is set or if the player is dying. Note: this property is writable since Open Surge 0.6.0. next next : number. The number of the next level in the current quest: 1 means the first level of the quest, 2 means the second, and so on. onUnload onUnload : object | null . Used to specify a function object to be called when the level is unloaded. debugMode debugMode : boolean. Whether or not the Debug Mode is activated. Available since: Open Surge 0.6.1 Functions spawn spawn(objectName) Spawns an object as a child of Level. Such objects won't be garbage collected. Use spawnEntity instead if you intend to spawn an entity . Arguments objectName : string. The name of the object to be spawned. Returns The spawned object. spawnEntity spawnEntity(objectName, position) Spawns an entity named objectName at a certain position . The entity won't be garbage collected, as in spawn . Arguments objectName : string. The name of the entity to be spawned. position : Vector2 object. The position of the entity. Returns The spawned entity object. entity entity(entityId) Entities spawned with spawnEntity are automatically assigned an ID, a hexadecimal identification string. The purpose of the ID is to uniquely identify the entity in the level. This function returns the entity whose ID is entityId . Arguments entityId : string. The ID of the entity to be retrieved. Returns The desired entity object, or null if there is no entity associated with the given ID. Example using SurgeEngine.Level ; // // Level.entity() is very useful when creating setup objects, i.e., // objects spawned when the level is initialized. You can use it to // tune the parameters of specific entities, call their functions, etc. // // The example below can be added to the startup list in the .lev file. // object \"My Setup Object\" { state \"main\" { // setup the entity item = Level . entity ( \"ab65d8fe1ebd68de\" ); // first, we get the entity if ( item != null ) { Console . print ( item . __name ); // then we print the object name //item.score = 100; // we can also change a property } else Console . print ( \"Entity not found\" ); // change the state state = \"done\" ; } state \"done\" { } } entityId entityId(entityObject) Returns the ID of the provided entity , if it is defined. If no such ID is defined, an empty string is returned. Available since: Open Surge 0.6.1 Arguments entityObject : object. An entity. Returns A string with a hexadecimal identification code, or an empty string. findEntity findEntity(entityName) Finds an entity named entityName spawned with spawnEntity . Available since: Open Surge 0.6.1 Arguments entityName : string. The name of an entity object. Returns An entity named entityName , or null if there is none. findEntities findEntities(entityName) Finds all entities named entityName spawned with spawnEntity . Available since: Open Surge 0.6.1 Arguments entityName : string. The name of the entities to be searched. Returns A new array containing all entities named entityName . If none are found, an empty array is returned. activeEntities activeEntities() Finds all active entities, i.e.: those that are near the camera, as well as all awake and detached ones. Available since: Open Surge 0.6.1 Returns A new array containing active entities. If none are found, an empty array is returned. setup setup(config) Sets up the properties of a collection of level objects. This is a handy function typically used in a startup object of your level. Its purpose is to configure the properties of level objects. You may set the properties of groups of objects (given their names) and of individual entities alone (given their IDs). The target properties and their respective values should be specified in the config Dictionary , passed as a parameter. Each key of config should be either an object name or an entity ID. Each value of the dictionary should be another dictionary specifying the properties to be set and their respective values. If an object name is specified in a key of config , all level objects with that name will be affected. If an entity ID is provided, only that specific entity will be affected, if it exists. This function will search for all the specified objects in the level, so it's not supposed to be used in a loop (or in a repeating state). Furthermore, if one or more objects or properties do not exist, this function will fail silently. Therefore, make sure you type everything correctly. Arguments config : Dictionary object. The configuration as described. Example using SurgeEngine.Level ; // // This is supposed to be a startup object, // listed in the startup list of a .lev file // object \"My Level Setup\" { // setup properties fun constructor () { Level . setup ({ \"Elevator\" : { \"anim\" : 2 }, \"Background Exchanger\" : { \"background\" : \"themes/template.bg\" }, \"5640353a6efd2901\" : { \"someProperty\" : 123 , \"someOtherProperty\" : \"hello\" }, \"770ae26584229af2\" : { \"title\" : \"Super!!\" , \"message\" : \"Hey there! Feeling good today?\" , \"buttons\" : [ \"Yes\" , \"No\" ] } }); } } restart restart() Restarts the current level. quit quit() Prompts the user to see if he/she wants to quit the current level. Deprecated since: Open Surge 0.6.1 abort abort() Quits the current level/quest without prompting the user. pause pause() Pauses the game. load load(filepath) Loads the specified level/quest. If you pass the path to a level (a .lev file in the levels/ folder), that level will be loaded. The state of the current level (position of the entities and so on) will be lost. If you pass the path to a quest (a .qst file in the quests/ folder), that quest will be loaded and, when it's completed or aborted, the engine will redirect the user back to the level he/she was before. Arguments filepath : string. Relative path of the level or quest to be loaded. Example using SurgeEngine.Level ; object \"My Level Loader\" { fun load ( id ) { if ( id == \"beach\" ) { Level . load ( \"levels/beach_level.lev\" ); } else if ( id == \"forest\" ) { Level . load ( \"levels/forest_level.lev\" ); } else if ( id == \"bonus\" ) { Level . next -= 1 ; // return to the current level after completing the bonus Level . load ( \"levels/bonus_stage.lev\" ); } else Console . print ( \"Unrecognized level: \" + id ); } } loadAndReturn loadAndReturn(filepath) Loads the specified level or quest and, after completing or exiting the loaded scene, returns to the level the player was before. If you pass the path to a quest, this function behaves exactly like load() . Available since: Open Surge 0.6.1 Arguments filepath : string. Relative path of the level or quest to be loaded. Example // Load a bonus stage and return to the current level if the player completes it or exits from it Level . loadAndReturn ( \"levels/bonus_stage.lev\" ); loadNext loadNext() Loads the next level in the current quest. This is the usual procedure after clearing the level . See also: next . clear clear() Sets the cleared flag and disables player input. See also: cleared , undoClear . undoClear undoClear() Reverses a previous call to clear , disabling the cleared flag and enabling player input again. This is typically used to play a cutscene after a level cleared animation or to have multiple acts in the same level file. See also: cleared , clear , act . Available since: Open Surge 0.6.1","title":"Level"},{"location":"engine/level/#level","text":"Level routines. A level is a scene in the game, stored as a .lev file in the levels/ folder. Whenever you spawn an object in SurgeScript, you must keep a reference to it, otherwise it will be automatically deleted by the Garbage Collector . Sometimes you want to spawn entities in your level, but keeping references to all of them is inconvenient. In this case, you can spawn them as children of the Level object . It will keep the references for you, and thus they won't be garbage collected. Example using SurgeEngine.Actor ; using SurgeEngine.Level ; using SurgeEngine.Vector2 ; object \"Application\" { state \"main\" { createExplosionAt ( 100 , 200 ); state = \"wait\" ; } state \"wait\" { if ( timeout ( 1.0 )) state = \"main\" ; } fun createExplosionAt ( x , y ) { position = Vector2 ( x , y ); return Level . spawnEntity ( \"MyExplosion\" , position ); // no need to keep references } } object \"MyExplosion\" is \"entity\" , \"disposable\" , \"private\" { actor = Actor ( \"MyExplosion\" ); state \"main\" { if ( actor . animation . finished ) destroy () } }","title":"Level"},{"location":"engine/level/#properties","text":"","title":"Properties"},{"location":"engine/level/#name","text":"name : string, read-only. The name of the level. Example using SurgeEngine.Level ; // Will display the name of the level object \"Application\" { state \"main\" { Console . print ( Level . name ); state = \"done\" ; } state \"done\" { } }","title":"name"},{"location":"engine/level/#act","text":"act : number. The act number (1, 2, 3...) of the current level. Note: this property is writable since Open Surge 0.6.1.","title":"act"},{"location":"engine/level/#cleared","text":"cleared : boolean, read-only. Checks if the current level has been cleared by the player. If this is true , a level cleared animation should be played. Although the engine provides a default animation, you may use this property to design your own. See also: clear .","title":"cleared"},{"location":"engine/level/#file","text":"file : string, read-only. The relative path of the .lev file of the current level.","title":"file"},{"location":"engine/level/#version","text":"version : string, read-only. The version of the level, defined in the .lev file.","title":"version"},{"location":"engine/level/#author","text":"author : string, read-only. The author of the level, defined in the .lev file.","title":"author"},{"location":"engine/level/#license","text":"license : string, read-only. The license of the level, defined in the .lev file.","title":"license"},{"location":"engine/level/#music","text":"music : Music object, read-only. The music of the level.","title":"music"},{"location":"engine/level/#bgtheme","text":"bgtheme : string, read-only. The path to the original background file (.bg), as declared in the .lev file.","title":"bgtheme"},{"location":"engine/level/#background","text":"background : string. The path to the background file (.bg) currently in use. Use this property to change the background of the level.","title":"background"},{"location":"engine/level/#waterlevel","text":"waterlevel : number. The y-coordinate, in world space, of the level water. Pixels not above this value are underwater.","title":"waterlevel"},{"location":"engine/level/#spawnpoint","text":"spawnpoint : Vector2 object. The position where the player is placed when the level starts.","title":"spawnpoint"},{"location":"engine/level/#gravity","text":"gravity : number, read-only. The acceleration of gravity, measured in pixels per second squared.","title":"gravity"},{"location":"engine/level/#time","text":"time : number. Elapsed time in the level, given in seconds. The level time will be frozen if the cleared flag is set or if the player is dying. Note: this property is writable since Open Surge 0.6.0.","title":"time"},{"location":"engine/level/#next","text":"next : number. The number of the next level in the current quest: 1 means the first level of the quest, 2 means the second, and so on.","title":"next"},{"location":"engine/level/#onunload","text":"onUnload : object | null . Used to specify a function object to be called when the level is unloaded.","title":"onUnload"},{"location":"engine/level/#debugmode","text":"debugMode : boolean. Whether or not the Debug Mode is activated. Available since: Open Surge 0.6.1","title":"debugMode"},{"location":"engine/level/#functions","text":"","title":"Functions"},{"location":"engine/level/#spawn","text":"spawn(objectName) Spawns an object as a child of Level. Such objects won't be garbage collected. Use spawnEntity instead if you intend to spawn an entity . Arguments objectName : string. The name of the object to be spawned. Returns The spawned object.","title":"spawn"},{"location":"engine/level/#spawnentity","text":"spawnEntity(objectName, position) Spawns an entity named objectName at a certain position . The entity won't be garbage collected, as in spawn . Arguments objectName : string. The name of the entity to be spawned. position : Vector2 object. The position of the entity. Returns The spawned entity object.","title":"spawnEntity"},{"location":"engine/level/#entity","text":"entity(entityId) Entities spawned with spawnEntity are automatically assigned an ID, a hexadecimal identification string. The purpose of the ID is to uniquely identify the entity in the level. This function returns the entity whose ID is entityId . Arguments entityId : string. The ID of the entity to be retrieved. Returns The desired entity object, or null if there is no entity associated with the given ID. Example using SurgeEngine.Level ; // // Level.entity() is very useful when creating setup objects, i.e., // objects spawned when the level is initialized. You can use it to // tune the parameters of specific entities, call their functions, etc. // // The example below can be added to the startup list in the .lev file. // object \"My Setup Object\" { state \"main\" { // setup the entity item = Level . entity ( \"ab65d8fe1ebd68de\" ); // first, we get the entity if ( item != null ) { Console . print ( item . __name ); // then we print the object name //item.score = 100; // we can also change a property } else Console . print ( \"Entity not found\" ); // change the state state = \"done\" ; } state \"done\" { } }","title":"entity"},{"location":"engine/level/#entityid","text":"entityId(entityObject) Returns the ID of the provided entity , if it is defined. If no such ID is defined, an empty string is returned. Available since: Open Surge 0.6.1 Arguments entityObject : object. An entity. Returns A string with a hexadecimal identification code, or an empty string.","title":"entityId"},{"location":"engine/level/#findentity","text":"findEntity(entityName) Finds an entity named entityName spawned with spawnEntity . Available since: Open Surge 0.6.1 Arguments entityName : string. The name of an entity object. Returns An entity named entityName , or null if there is none.","title":"findEntity"},{"location":"engine/level/#findentities","text":"findEntities(entityName) Finds all entities named entityName spawned with spawnEntity . Available since: Open Surge 0.6.1 Arguments entityName : string. The name of the entities to be searched. Returns A new array containing all entities named entityName . If none are found, an empty array is returned.","title":"findEntities"},{"location":"engine/level/#activeentities","text":"activeEntities() Finds all active entities, i.e.: those that are near the camera, as well as all awake and detached ones. Available since: Open Surge 0.6.1 Returns A new array containing active entities. If none are found, an empty array is returned.","title":"activeEntities"},{"location":"engine/level/#setup","text":"setup(config) Sets up the properties of a collection of level objects. This is a handy function typically used in a startup object of your level. Its purpose is to configure the properties of level objects. You may set the properties of groups of objects (given their names) and of individual entities alone (given their IDs). The target properties and their respective values should be specified in the config Dictionary , passed as a parameter. Each key of config should be either an object name or an entity ID. Each value of the dictionary should be another dictionary specifying the properties to be set and their respective values. If an object name is specified in a key of config , all level objects with that name will be affected. If an entity ID is provided, only that specific entity will be affected, if it exists. This function will search for all the specified objects in the level, so it's not supposed to be used in a loop (or in a repeating state). Furthermore, if one or more objects or properties do not exist, this function will fail silently. Therefore, make sure you type everything correctly. Arguments config : Dictionary object. The configuration as described. Example using SurgeEngine.Level ; // // This is supposed to be a startup object, // listed in the startup list of a .lev file // object \"My Level Setup\" { // setup properties fun constructor () { Level . setup ({ \"Elevator\" : { \"anim\" : 2 }, \"Background Exchanger\" : { \"background\" : \"themes/template.bg\" }, \"5640353a6efd2901\" : { \"someProperty\" : 123 , \"someOtherProperty\" : \"hello\" }, \"770ae26584229af2\" : { \"title\" : \"Super!!\" , \"message\" : \"Hey there! Feeling good today?\" , \"buttons\" : [ \"Yes\" , \"No\" ] } }); } }","title":"setup"},{"location":"engine/level/#restart","text":"restart() Restarts the current level.","title":"restart"},{"location":"engine/level/#quit","text":"quit() Prompts the user to see if he/she wants to quit the current level. Deprecated since: Open Surge 0.6.1","title":"quit"},{"location":"engine/level/#abort","text":"abort() Quits the current level/quest without prompting the user.","title":"abort"},{"location":"engine/level/#pause","text":"pause() Pauses the game.","title":"pause"},{"location":"engine/level/#load","text":"load(filepath) Loads the specified level/quest. If you pass the path to a level (a .lev file in the levels/ folder), that level will be loaded. The state of the current level (position of the entities and so on) will be lost. If you pass the path to a quest (a .qst file in the quests/ folder), that quest will be loaded and, when it's completed or aborted, the engine will redirect the user back to the level he/she was before. Arguments filepath : string. Relative path of the level or quest to be loaded. Example using SurgeEngine.Level ; object \"My Level Loader\" { fun load ( id ) { if ( id == \"beach\" ) { Level . load ( \"levels/beach_level.lev\" ); } else if ( id == \"forest\" ) { Level . load ( \"levels/forest_level.lev\" ); } else if ( id == \"bonus\" ) { Level . next -= 1 ; // return to the current level after completing the bonus Level . load ( \"levels/bonus_stage.lev\" ); } else Console . print ( \"Unrecognized level: \" + id ); } }","title":"load"},{"location":"engine/level/#loadandreturn","text":"loadAndReturn(filepath) Loads the specified level or quest and, after completing or exiting the loaded scene, returns to the level the player was before. If you pass the path to a quest, this function behaves exactly like load() . Available since: Open Surge 0.6.1 Arguments filepath : string. Relative path of the level or quest to be loaded. Example // Load a bonus stage and return to the current level if the player completes it or exits from it Level . loadAndReturn ( \"levels/bonus_stage.lev\" );","title":"loadAndReturn"},{"location":"engine/level/#loadnext","text":"loadNext() Loads the next level in the current quest. This is the usual procedure after clearing the level . See also: next .","title":"loadNext"},{"location":"engine/level/#clear","text":"clear() Sets the cleared flag and disables player input. See also: cleared , undoClear .","title":"clear"},{"location":"engine/level/#undoclear","text":"undoClear() Reverses a previous call to clear , disabling the cleared flag and enabling player input again. This is typically used to play a cutscene after a level cleared animation or to have multiple acts in the same level file. See also: cleared , clear , act . Available since: Open Surge 0.6.1","title":"undoClear"},{"location":"engine/mobile_gamepad/","text":"MobileGamepad The mobile gamepad is a virtual gamepad that appears on the screen when the engine is launched in mobile mode . Available since: Open Surge 0.6.1 Properties visible visible : boolean, read-only. Whether or not the mobile gamepad is visible. Functions fadeIn fadeIn() Makes the mobile gamepad appear smoothly. fadeOut fadeOut() Makes the mobile gamepad disappear smoothly.","title":"MobileGamepad"},{"location":"engine/mobile_gamepad/#mobilegamepad","text":"The mobile gamepad is a virtual gamepad that appears on the screen when the engine is launched in mobile mode . Available since: Open Surge 0.6.1","title":"MobileGamepad"},{"location":"engine/mobile_gamepad/#properties","text":"","title":"Properties"},{"location":"engine/mobile_gamepad/#visible","text":"visible : boolean, read-only. Whether or not the mobile gamepad is visible.","title":"visible"},{"location":"engine/mobile_gamepad/#functions","text":"","title":"Functions"},{"location":"engine/mobile_gamepad/#fadein","text":"fadeIn() Makes the mobile gamepad appear smoothly.","title":"fadeIn"},{"location":"engine/mobile_gamepad/#fadeout","text":"fadeOut() Makes the mobile gamepad disappear smoothly.","title":"fadeOut"},{"location":"engine/mouse/","text":"Mouse The Mouse object is used to read input from the mouse. Example // This example shows how to use a sprite // as a mouse cursor. Since My Cursor is // tagged \"detached\", it will be rendered // in screen space, not in world space. using SurgeEngine.Actor ; using SurgeEngine.Transform ; using SurgeEngine.Input.Mouse ; object \"My Cursor\" is \"entity\" , \"detached\" { actor = Actor ( \"My Cursor\" ); transform = Transform (); state \"main\" { transform . position = Mouse . position ; if ( Mouse . buttonPressed ( \"left\" )) Console . print ( \"left click\" ); } fun constructor () { actor . zindex = 1.0 ; } } Properties position position : Vector2 object, read-only. The position of the mouse cursor, in screen space. scrollUp scrollUp : boolean, read-only. Will be true at the frame the user scrolls up using the mouse wheel. Available since: Open Surge 0.5.1 scrollDown scrollDown : boolean, read-only. Will be true at the frame the user scrolls down using the mouse wheel. Available since: Open Surge 0.5.1 Functions buttonDown buttonDown(buttonName) Checks if a mouse button is currently being held down. Arguments buttonName : string. One of the following: \"left\" , \"right\" , \"middle\" . Returns Returns true if the specified button is being held down. buttonPressed buttonPressed(buttonName) Checks if a mouse button has just been pressed. Arguments buttonName : string. One of the following: \"left\" , \"right\" , \"middle\" . Returns Returns true if the specified button has just been pressed (i.e., a click has just occurred). Example using SurgeEngine.Input.Mouse ; using SurgeEngine.Collisions.CollisionBall ; using SurgeEngine.Transform ; using SurgeEngine.Camera ; // Use the mouse cursor to click on any entity that has a collider. // Setup: simply place this object on the level. object \"Entity Picker\" is \"awake\" , \"entity\" { transform = Transform (); collider = CollisionBall ( 8 ); state \"main\" { transform . position = Camera . screenToWorld ( Mouse . position ); collider . visible = true ; } fun onOverlap ( otherCollider ) { if ( Mouse . buttonPressed ( \"left\" )) Console . print ( \"Clicked on \" + otherCollider . entity . __name ); } } buttonReleased buttonReleased(buttonName) Checks if a mouse button has just been released. Arguments buttonName : string. One of the following: \"left\" , \"right\" , \"middle\" . Returns Returns true if the specified button has just been released.","title":"Mouse"},{"location":"engine/mouse/#mouse","text":"The Mouse object is used to read input from the mouse. Example // This example shows how to use a sprite // as a mouse cursor. Since My Cursor is // tagged \"detached\", it will be rendered // in screen space, not in world space. using SurgeEngine.Actor ; using SurgeEngine.Transform ; using SurgeEngine.Input.Mouse ; object \"My Cursor\" is \"entity\" , \"detached\" { actor = Actor ( \"My Cursor\" ); transform = Transform (); state \"main\" { transform . position = Mouse . position ; if ( Mouse . buttonPressed ( \"left\" )) Console . print ( \"left click\" ); } fun constructor () { actor . zindex = 1.0 ; } }","title":"Mouse"},{"location":"engine/mouse/#properties","text":"","title":"Properties"},{"location":"engine/mouse/#position","text":"position : Vector2 object, read-only. The position of the mouse cursor, in screen space.","title":"position"},{"location":"engine/mouse/#scrollup","text":"scrollUp : boolean, read-only. Will be true at the frame the user scrolls up using the mouse wheel. Available since: Open Surge 0.5.1","title":"scrollUp"},{"location":"engine/mouse/#scrolldown","text":"scrollDown : boolean, read-only. Will be true at the frame the user scrolls down using the mouse wheel. Available since: Open Surge 0.5.1","title":"scrollDown"},{"location":"engine/mouse/#functions","text":"","title":"Functions"},{"location":"engine/mouse/#buttondown","text":"buttonDown(buttonName) Checks if a mouse button is currently being held down. Arguments buttonName : string. One of the following: \"left\" , \"right\" , \"middle\" . Returns Returns true if the specified button is being held down.","title":"buttonDown"},{"location":"engine/mouse/#buttonpressed","text":"buttonPressed(buttonName) Checks if a mouse button has just been pressed. Arguments buttonName : string. One of the following: \"left\" , \"right\" , \"middle\" . Returns Returns true if the specified button has just been pressed (i.e., a click has just occurred). Example using SurgeEngine.Input.Mouse ; using SurgeEngine.Collisions.CollisionBall ; using SurgeEngine.Transform ; using SurgeEngine.Camera ; // Use the mouse cursor to click on any entity that has a collider. // Setup: simply place this object on the level. object \"Entity Picker\" is \"awake\" , \"entity\" { transform = Transform (); collider = CollisionBall ( 8 ); state \"main\" { transform . position = Camera . screenToWorld ( Mouse . position ); collider . visible = true ; } fun onOverlap ( otherCollider ) { if ( Mouse . buttonPressed ( \"left\" )) Console . print ( \"Clicked on \" + otherCollider . entity . __name ); } }","title":"buttonPressed"},{"location":"engine/mouse/#buttonreleased","text":"buttonReleased(buttonName) Checks if a mouse button has just been released. Arguments buttonName : string. One of the following: \"left\" , \"right\" , \"middle\" . Returns Returns true if the specified button has just been released.","title":"buttonReleased"},{"location":"engine/music/","text":"Music The Music object lets you play music. This is meant to handle background music; therefore, only one music can be played at a time. Unlike regular sounds , musics are streamed, (i.e., not loaded completely in memory). Given the longer nature of musics, this improves memory usage and helps with the loading times. Example using SurgeEngine.Level ; // Fades the music in a linear fashion ;) object \"MyMusicFader\" { public music = Level . music ; prevVolume = music . volume ; fadeTime = 1.0 ; // given in seconds state \"main\" { } state \"fadeout\" { music . volume -= Time . delta / fadeTime ; if ( music . volume <= 0.0 ) { music . pause (); music . volume = prevVolume ; state = \"main\" ; } } // call fadeOut() to make the // music fade smoothly fun fadeOut ( seconds ) { if ( state == \"main\" ) prevVolume = music . volume ; fadeTime = seconds ; state = \"fadeout\" ; } } Factory Music Audio.Music(path) Creates a Music object associated with a certain file. Arguments path : string. The path of the music - usually a file in the musics/ folder. Returns A Music object. Example using SurgeEngine.Audio.Music ; object \"MusicTest\" { music = Music ( \"musics/options.ogg\" ); state \"main\" { // loop music if (! music . playing ) music . play (); } } Properties playing playing : boolean, read-only. Will be true if the music is playing. volume volume : number. The volume of the music, a value between 0.0 and 1.0, inclusive (zero means silence). Functions play play() Plays the music (once). To make it loop, play it whenever music.playing is false . stop stop() Stops the music. Once the music is stopped, it can only be played again from the beginning. pause pause() Pauses the music. A paused music can be resumed later with play() .","title":"Music"},{"location":"engine/music/#music","text":"The Music object lets you play music. This is meant to handle background music; therefore, only one music can be played at a time. Unlike regular sounds , musics are streamed, (i.e., not loaded completely in memory). Given the longer nature of musics, this improves memory usage and helps with the loading times. Example using SurgeEngine.Level ; // Fades the music in a linear fashion ;) object \"MyMusicFader\" { public music = Level . music ; prevVolume = music . volume ; fadeTime = 1.0 ; // given in seconds state \"main\" { } state \"fadeout\" { music . volume -= Time . delta / fadeTime ; if ( music . volume <= 0.0 ) { music . pause (); music . volume = prevVolume ; state = \"main\" ; } } // call fadeOut() to make the // music fade smoothly fun fadeOut ( seconds ) { if ( state == \"main\" ) prevVolume = music . volume ; fadeTime = seconds ; state = \"fadeout\" ; } }","title":"Music"},{"location":"engine/music/#factory","text":"","title":"Factory"},{"location":"engine/music/#music_1","text":"Audio.Music(path) Creates a Music object associated with a certain file. Arguments path : string. The path of the music - usually a file in the musics/ folder. Returns A Music object. Example using SurgeEngine.Audio.Music ; object \"MusicTest\" { music = Music ( \"musics/options.ogg\" ); state \"main\" { // loop music if (! music . playing ) music . play (); } }","title":"Music"},{"location":"engine/music/#properties","text":"","title":"Properties"},{"location":"engine/music/#playing","text":"playing : boolean, read-only. Will be true if the music is playing.","title":"playing"},{"location":"engine/music/#volume","text":"volume : number. The volume of the music, a value between 0.0 and 1.0, inclusive (zero means silence).","title":"volume"},{"location":"engine/music/#functions","text":"","title":"Functions"},{"location":"engine/music/#play","text":"play() Plays the music (once). To make it loop, play it whenever music.playing is false .","title":"play"},{"location":"engine/music/#stop","text":"stop() Stops the music. Once the music is stopped, it can only be played again from the beginning.","title":"stop"},{"location":"engine/music/#pause","text":"pause() Pauses the music. A paused music can be resumed later with play() .","title":"pause"},{"location":"engine/platform/","text":"Platform Routines specific to the platform the game engine is currently running on. Available since : Open Surge 0.6.1 Example // Let's find out which platform the game engine is currently running on using SurgeEngine.Platform ; object \"Application\" { state \"main\" { Console . print ( platformName ()); state = \"done\" ; } state \"done\" { } fun platformName () { if ( Platform . isAndroid ) return \"Android\" ; else if ( Platform . isWindows ) return \"Windows\" ; else if ( Platform . isMacOS ) return \"macOS\" ; else if ( Platform . isUnix ) return \"Unix\" ; else return \"Unknown\" ; } } Properties isWindows isWindows : boolean, read-only. Will be true if the game engine is running on Microsoft Windows. isUnix isUnix : boolean, read-only. Will be true if the game engine is running on a Unix-like operating system such as: Linux, BSD, macOS, Android, etc. isMacOS isMacOS : boolean, read-only. Will be true if the game engine is running on macOS. isAndroid isAndroid : boolean, read-only. Will be true if the game engine is running on Android. Check SurgeEngine.mobile instead if you want to know if the game engine is running on mobile mode.","title":"Platform"},{"location":"engine/platform/#platform","text":"Routines specific to the platform the game engine is currently running on. Available since : Open Surge 0.6.1 Example // Let's find out which platform the game engine is currently running on using SurgeEngine.Platform ; object \"Application\" { state \"main\" { Console . print ( platformName ()); state = \"done\" ; } state \"done\" { } fun platformName () { if ( Platform . isAndroid ) return \"Android\" ; else if ( Platform . isWindows ) return \"Windows\" ; else if ( Platform . isMacOS ) return \"macOS\" ; else if ( Platform . isUnix ) return \"Unix\" ; else return \"Unknown\" ; } }","title":"Platform"},{"location":"engine/platform/#properties","text":"","title":"Properties"},{"location":"engine/platform/#iswindows","text":"isWindows : boolean, read-only. Will be true if the game engine is running on Microsoft Windows.","title":"isWindows"},{"location":"engine/platform/#isunix","text":"isUnix : boolean, read-only. Will be true if the game engine is running on a Unix-like operating system such as: Linux, BSD, macOS, Android, etc.","title":"isUnix"},{"location":"engine/platform/#ismacos","text":"isMacOS : boolean, read-only. Will be true if the game engine is running on macOS.","title":"isMacOS"},{"location":"engine/platform/#isandroid","text":"isAndroid : boolean, read-only. Will be true if the game engine is running on Android. Check SurgeEngine.mobile instead if you want to know if the game engine is running on mobile mode.","title":"isAndroid"},{"location":"engine/platformer/","text":"Platformer The Platformer behavior makes the associated entity perform a simple platform movement (with gravity, etc). Used mostly by NPCs and baddies, this behavior is supposed to be lightweight for the CPU and is not designed to support 360\u00b0-physics. Important: for best results, the hot spot of the entity should be placed on its feet. Example // // In the example below, we create a dummy that // walks around the level (left and right) // using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.Platformer ; object \"My Baddie\" is \"entity\" , \"enemy\" { actor = Actor ( \"My Baddie\" ); // give it graphics enemy = Enemy (); // make it behave like a baddie platformer = Platformer (); // give it a platform movement state \"main\" { platformer . speed = 60 ; // 60 pixels per second platformer . walk (); // make it walk } } Factory Behaviors.Platformer Platformer() Spawns a Platformer. Returns The behavior object. Properties speed speed : number. Walking speed, in pixels per second. jumpSpeed jumpSpeed : number. Jump speed, in pixels per second. The higher the value, the more intense the jump. gravityMultiplier gravityMultiplier : number. A multiplier used to modify how the Platformer is affected by gravity. When set to 1.0, the Platformer will subject to the default acceleration of gravity . When set to 2.0 (0.5), the Platformer will be subject to twice (half) the default gravity, and so on. Zero means no gravity. Defaults to 1.0. Available since: Open Surge 0.6.0 direction direction : number, read-only. Direction will be +1 if the platformer is facing right or -1 is it's facing left. walking walking : boolean, read-only. Is the platformer walking? walkingLeft walkingLeft : boolean, read-only. Is the platformer walking to the left? walkingRight walkingRight : boolean, read-only. Is the platformer walking to the right? midair midair : boolean, read-only. Is the platformer midair? falling falling : boolean, read-only. Is the platformer falling down? wall wall : boolean, read-only. Is the platformer touching a wall? leftWall leftWall : boolean, read-only. Is the platformer touching a wall on its left side? rightWall rightWall : boolean, read-only. Is the platformer touching a wall on its right side? leftLedge leftLedge : boolean, read-only. Is the platformer standing on a ledge located on its left side? rightLedge rightLedge : boolean, read-only. Is the platformer standing on a ledge located on its right side? Functions walk walk() Enables automatic walking. The platformer will walk left and right automatically. Returns Returns the platformer itself. walkLeft walkLeft() Makes the platformer walk to the left. Returns Returns the platformer itself. walkRight walkRight() Makes the platformer walk to the right. Returns Returns the platformer itself. stop stop() Makes the platformer stop walking. Returns Returns the platformer itself. jump jump() Makes the platformer jump. It will only jump if it's touching the ground. Returns Returns the platformer itself. Example // // In the example below, we create a jumping // dummy that walks left and right // using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.Platformer ; object \"My Jumping Baddie\" is \"entity\" , \"enemy\" { actor = Actor ( \"My Jumping Baddie\" ); // handles the graphics enemy = Enemy (); // make it behave like a baddie platformer = Platformer (). walk (); // make it walk state \"main\" { platformer . speed = 60 ; // 60 pixels per second if ( timeout ( 3.0 )) // jump every 3 seconds state = \"jump\" ; } state \"jump\" { platformer . jump (); state = \"main\" ; } } forceJump forceJump(speed) Makes the platformer jump, regardless if it's touching the ground or not. Arguments speed : number. Jump speed in pixels per second. Returns Returns the platformer itself. setSensorBox setSensorBox(width, height) The platformer spawns invisible sensors to detect collisions. Together, these sensors are thought to form a box which size is related to the size of the individual sensors. This function sets the size of this box. That size should be compatible with the size of the sprite and a size too small may break the platformer. The size of the sensor box is computed automatically, so normally you don't need to modify it. Arguments width : number. The width of the box, in pixels. height : number. The height of the box, in pixels. Returns Returns the platformer itself. showSensors showSensors() Displays the internal sensors of the platformer, which are invisible by default. For debugging only. Available since: Open Surge 0.5.2 Returns Returns the platformer itself. Example using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Platformer ; object \"Testing Stuff\" is \"entity\" { actor = Actor ( \"Testing Stuff\" ); platformer = Platformer (). showSensors (); // ... } hideSensors hideSensors() Hides the internal sensors of the platformer. This is the default. Available since: Open Surge 0.5.2 Returns Returns the platformer itself.","title":"Platformer"},{"location":"engine/platformer/#platformer","text":"The Platformer behavior makes the associated entity perform a simple platform movement (with gravity, etc). Used mostly by NPCs and baddies, this behavior is supposed to be lightweight for the CPU and is not designed to support 360\u00b0-physics. Important: for best results, the hot spot of the entity should be placed on its feet. Example // // In the example below, we create a dummy that // walks around the level (left and right) // using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.Platformer ; object \"My Baddie\" is \"entity\" , \"enemy\" { actor = Actor ( \"My Baddie\" ); // give it graphics enemy = Enemy (); // make it behave like a baddie platformer = Platformer (); // give it a platform movement state \"main\" { platformer . speed = 60 ; // 60 pixels per second platformer . walk (); // make it walk } }","title":"Platformer"},{"location":"engine/platformer/#factory","text":"","title":"Factory"},{"location":"engine/platformer/#behaviorsplatformer","text":"Platformer() Spawns a Platformer. Returns The behavior object.","title":"Behaviors.Platformer"},{"location":"engine/platformer/#properties","text":"","title":"Properties"},{"location":"engine/platformer/#speed","text":"speed : number. Walking speed, in pixels per second.","title":"speed"},{"location":"engine/platformer/#jumpspeed","text":"jumpSpeed : number. Jump speed, in pixels per second. The higher the value, the more intense the jump.","title":"jumpSpeed"},{"location":"engine/platformer/#gravitymultiplier","text":"gravityMultiplier : number. A multiplier used to modify how the Platformer is affected by gravity. When set to 1.0, the Platformer will subject to the default acceleration of gravity . When set to 2.0 (0.5), the Platformer will be subject to twice (half) the default gravity, and so on. Zero means no gravity. Defaults to 1.0. Available since: Open Surge 0.6.0","title":"gravityMultiplier"},{"location":"engine/platformer/#direction","text":"direction : number, read-only. Direction will be +1 if the platformer is facing right or -1 is it's facing left.","title":"direction"},{"location":"engine/platformer/#walking","text":"walking : boolean, read-only. Is the platformer walking?","title":"walking"},{"location":"engine/platformer/#walkingleft","text":"walkingLeft : boolean, read-only. Is the platformer walking to the left?","title":"walkingLeft"},{"location":"engine/platformer/#walkingright","text":"walkingRight : boolean, read-only. Is the platformer walking to the right?","title":"walkingRight"},{"location":"engine/platformer/#midair","text":"midair : boolean, read-only. Is the platformer midair?","title":"midair"},{"location":"engine/platformer/#falling","text":"falling : boolean, read-only. Is the platformer falling down?","title":"falling"},{"location":"engine/platformer/#wall","text":"wall : boolean, read-only. Is the platformer touching a wall?","title":"wall"},{"location":"engine/platformer/#leftwall","text":"leftWall : boolean, read-only. Is the platformer touching a wall on its left side?","title":"leftWall"},{"location":"engine/platformer/#rightwall","text":"rightWall : boolean, read-only. Is the platformer touching a wall on its right side?","title":"rightWall"},{"location":"engine/platformer/#leftledge","text":"leftLedge : boolean, read-only. Is the platformer standing on a ledge located on its left side?","title":"leftLedge"},{"location":"engine/platformer/#rightledge","text":"rightLedge : boolean, read-only. Is the platformer standing on a ledge located on its right side?","title":"rightLedge"},{"location":"engine/platformer/#functions","text":"","title":"Functions"},{"location":"engine/platformer/#walk","text":"walk() Enables automatic walking. The platformer will walk left and right automatically. Returns Returns the platformer itself.","title":"walk"},{"location":"engine/platformer/#walkleft","text":"walkLeft() Makes the platformer walk to the left. Returns Returns the platformer itself.","title":"walkLeft"},{"location":"engine/platformer/#walkright","text":"walkRight() Makes the platformer walk to the right. Returns Returns the platformer itself.","title":"walkRight"},{"location":"engine/platformer/#stop","text":"stop() Makes the platformer stop walking. Returns Returns the platformer itself.","title":"stop"},{"location":"engine/platformer/#jump","text":"jump() Makes the platformer jump. It will only jump if it's touching the ground. Returns Returns the platformer itself. Example // // In the example below, we create a jumping // dummy that walks left and right // using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Enemy ; using SurgeEngine.Behaviors.Platformer ; object \"My Jumping Baddie\" is \"entity\" , \"enemy\" { actor = Actor ( \"My Jumping Baddie\" ); // handles the graphics enemy = Enemy (); // make it behave like a baddie platformer = Platformer (). walk (); // make it walk state \"main\" { platformer . speed = 60 ; // 60 pixels per second if ( timeout ( 3.0 )) // jump every 3 seconds state = \"jump\" ; } state \"jump\" { platformer . jump (); state = \"main\" ; } }","title":"jump"},{"location":"engine/platformer/#forcejump","text":"forceJump(speed) Makes the platformer jump, regardless if it's touching the ground or not. Arguments speed : number. Jump speed in pixels per second. Returns Returns the platformer itself.","title":"forceJump"},{"location":"engine/platformer/#setsensorbox","text":"setSensorBox(width, height) The platformer spawns invisible sensors to detect collisions. Together, these sensors are thought to form a box which size is related to the size of the individual sensors. This function sets the size of this box. That size should be compatible with the size of the sprite and a size too small may break the platformer. The size of the sensor box is computed automatically, so normally you don't need to modify it. Arguments width : number. The width of the box, in pixels. height : number. The height of the box, in pixels. Returns Returns the platformer itself.","title":"setSensorBox"},{"location":"engine/platformer/#showsensors","text":"showSensors() Displays the internal sensors of the platformer, which are invisible by default. For debugging only. Available since: Open Surge 0.5.2 Returns Returns the platformer itself. Example using SurgeEngine.Actor ; using SurgeEngine.Behaviors.Platformer ; object \"Testing Stuff\" is \"entity\" { actor = Actor ( \"Testing Stuff\" ); platformer = Platformer (). showSensors (); // ... }","title":"showSensors"},{"location":"engine/platformer/#hidesensors","text":"hideSensors() Hides the internal sensors of the platformer. This is the default. Available since: Open Surge 0.5.2 Returns Returns the platformer itself.","title":"hideSensors"},{"location":"engine/player/","text":"Player The Player object is used to control a specific player/character. Player objects are tagged player . Note: in Open Surge, companion objects can be used to give new abilities to players. Companion objects must be indicated in the character definition files (.chr) and are implemented as regular scripts. The engine will automatically spawn the companions as children of the appropriate Player objects. Example object \"Display player name\" is \"companion\" { player = parent ; // since this object is configured as a // companion, parent is the reference // to the appropriate Player object state \"main\" { Console . print ( \"I am a companion of \" + player . name ); } } Global Player Player(playerName) Gets the Player object associated with a character in the level. If a player with the specified name doesn't exist in the level, there will be an error. See also: exists . Arguments playerName : string. The name of a character, as defined in a .chr file stored in the characters/ folder. Returns A Player object. Example using SurgeEngine.Player ; // Gives Surge 1 collectible each second // Just place it in your level object \"Collectible Giver\" is \"entity\" , \"awake\" { player = Player ( \"Surge\" ); state \"main\" { if ( timeout ( 1 )) state = \"give collectible\" ; } state \"give collectible\" { player . collectibles = player . collectibles + 1 ; state = \"main\" ; } } Player.get Player[i] Gets a Player object by its sequence number, as defined in the players entry of the level file. See also: count . Arguments i : number. An integer between 0 and Player.count - 1 , inclusive. Returns A Player object. Player.exists Player.exists(playerName) Checks if a player named playerName exists in the level. Arguments playerName : string. The name of a character. Returns Returns true if such a player exists in the level. Player.active Player.active : Player object. The player currently in focus. See also: focus , hasFocus , focusable . Example using SurgeEngine.Player ; // Tells the name of the active player // Just place it in the level object \"Who am I\" is \"entity\" , \"awake\" { state \"main\" { player = Player . active ; Console . print ( \"I am \" + player . name ); destroy (); } } Player.count Player.count : number, read-only. The number of players in the level. Player.initialLives Player.initialLives : number, read-only. The initial number of lives set by the engine. Properties id id : number, read-only. A number that uniquely identifies the player in the Level. See also: name . Available since: Open Surge 0.6.1 name name : string, read-only. The name of the character. See also: id . direction direction : number, read-only. This number will be +1 if the player is facing right, or -1 if facing left. See also: hflip . Example // let's check if the player is facing right or left isFacingRight = ( player . direction > 0 ); isFacingLeft = ( player . direction < 0 ); input input : Input object, read-only. Reference to the Input object of the Player. Example using SurgeEngine.Player ; object \"Application\" { state \"main\" { player = Player . active ; if ( player . input . buttonDown ( \"right\" )) Console . print ( \"Player is holding right\" ); } } animation animation : Animation object, read-only. Reference to the Animation object of the Player. See also: anim . anim anim : number. A shortcut to animation.id : an integer corresponding to the current animation number. See also: animation , id . anchor anchor : Vector2 object. A shortcut to animation.anchor . See also: anchor . Available since: Open Surge 0.6.0 hotSpot hotSpot : Vector2 object. A shortcut to animation.hotSpot . See also: hotSpot . Available since: Open Surge 0.6.0. Note: in versions prior to 0.6.0, you may get the hot spot using the Animation object. actionSpot actionSpot : Vector2 object. A shortcut to animation.actionSpot . See also: actionSpot . Available since: Open Surge 0.6.0 actionOffset actionOffset : Vector2 object, read-only. A shortcut to animation.actionOffset . See also: actionOffset . Available since: Open Surge 0.6.0 attacking attacking : boolean, read-only. Is the player attacking, i.e., jumping, rolling, charging or invincible? This flag will be modified if the player is aggressive or inoffensive. See also: aggressive , inoffensive . midair midair : boolean, read-only. Is the player midair? stopped stopped : boolean, read-only. Is the player stopped? walking walking : boolean, read-only. Is the player walking? running running : boolean, read-only. Is the player running? jumping jumping : boolean, read-only. Is the player jumping? springing springing : boolean, read-only. Is the player playing the \"springing\" animation, displayed just after hitting a spring? braking braking : boolean, read-only. Is the player braking? balancing balancing : boolean, read-only. Is the player balancing on a ledge? waiting waiting : boolean, read-only. Is the player waiting? (happens after remaining stopped for a few seconds) rolling rolling : boolean, read-only. Is the player rolling? charging charging : boolean, read-only. Is the player charging a rolling movement? pushing pushing : boolean, read-only. Is the player pushing a wall? hit hit : boolean, read-only. Is the player getting hit (i.e., losing collectibles or a shield)? See also: getHit . blinking blinking : boolean, read-only. Is the player blinking? (happens just after getting hit) dying dying : boolean, read-only. Is the player dying or drowning? drowning drowning : boolean, read-only. Is the player drowning (i.e., dying underwater)? See also: underwater , dying . breathing breathing : boolean, read-only. Is the player breathing an air bubble that is underwater? See also: underwater , breathTime . crouchingDown crouchingDown : boolean, read-only. Is the player crouching down? lookingUp lookingUp : boolean, read-only. Is the player looking up? winning winning : boolean, read-only. Is the player displaying the \"winning\" animation (after clearing a level)? underwater underwater : boolean, read-only. Is the player underwater? Players are considered to be underwater if they are below the water level or if their forciblyUnderwater flag is set to true . See also: secondsToDrown , drowning , breathing , breathTime , forciblyUnderwater , forciblyOutOfWater , waterlevel . secondsToDrown secondsToDrown : number, read-only. The number of seconds to drown, if underwater. See also: underwater , drowning , breathTime . topspeed topspeed : number, read-only. The maximum speed that the player can reach when running naturally, without rolling and with no external forces applied. Given in pixels per second. See also: capspeed . capspeed capspeed : number, read-only. The maximum speed that the player can reach by normal means (e.g., rolling downhill), not considering external forces. Given in pixels per second. See also: topspeed . Available since: Open Surge 0.6.1 hlockTime hlockTime : number, read-only. The time, in seconds, in which the player will not respond to horizontal input when on the ground. Defaults to zero. See also: hlock . Available since: Open Surge 0.6.1 transform transform : Transform object, read-only. The transform of the Player. collider collider : Collider object, read-only. A collider associated with this Player. shield shield : string | null . One of the following: \"shield\" , \"fire\" , \"thunder\" , \"water\" , \"acid\" , \"wind\" or null (if there is no shield). See also: invulnerable . invincible invincible : boolean. Used to make the player invincible. Defaults to false . turbo turbo : boolean. Turbocharged mode (increases player speed). Defaults to false . frozen frozen : boolean. Disable/enable player movement. Defaults to false . aggressive aggressive : boolean. If set to true , the attacking flag will be true regardless of the state of the player. The player will be able to hit the baddies just by touching them. Defaults to false . See also: attacking , inoffensive . Available since: Open Surge 0.5.1 inoffensive inoffensive : boolean. If set to true , the attacking flag will be false regardless of the state of the player. The player will be vulnerable to damage even if jumping, rolling or charging. Defaults to false . Note: if the player is simultaneously aggressive and inoffensive, the aggressive behavior prevails. See also: attacking , aggressive . Available since: Open Surge 0.6.1 invulnerable invulnerable : boolean. If set to true , the player will be invulnerable to damage. It's like having an invisible shield that is permanent. The player may still be killed if crushed, by falling into a pit, by drowning, or by calling kill . Available since: Open Surge 0.6.1 immortal immortal : boolean. If an immortal player appears to be killed, it will appear to be ressurrected on its spawn point without losing a life . See also: lives . Available since: Open Surge 0.6.1 secondary secondary : boolean. A secondary player plays a secondary role and interacts with items in different ways. It cannot smash item boxes, activate goal signs, etc. This flag is best used with AI-controlled players. Defaults to false . Available since: Open Surge 0.6.1 focusable focusable : boolean. A focusable player can receive focus. Defaults to true . See also: focus , hasFocus , Player.active . Available since: Open Surge 0.6.1 Note: if only a single player exists in the level, then that player will have focus regardless of the value of this flag. breathTime breathTime : number. The maximum number of seconds the player can remain underwater without breathing. See also: underwater , secondsToDrown . forciblyUnderwater forciblyUnderwater : boolean. If set to true , the underwater flag will be true regardless of the water level . If set to false , the underwater flag will be true only if the player is below the water level. Defaults to false . See also: underwater , waterlevel , forciblyOutOfWater . Available since: Open Surge 0.6.1 forciblyOutOfWater If set to true , the underwater mechanics will be disabled, even if the player is below the water level . If forciblyUnderwater is also true , this flag will do nothing. Defaults to false . See also: underwater , waterlevel , forciblyUnderwater . Available since: Open Surge 0.6.1 layer layer : string. The current layer of the player. One of the following: \"green\" , \"yellow\" , \"default\" . This property tells you which bricks will be sensed, depending on their layer. visible visible : boolean. Should the player sprite be rendered? Defaults to true . collectibles collectibles : number. The number of collectibles, an integer shared between all player objects. lives lives : number. The number of lives, an integer shared between all player objects. score score : number. The score of the player, an integer value shared between all player objects. speed speed : number. The speed of the player, in pixels per second. This will be mapped automatically to gsp or xsp , depending on whether the player is touching the ground or not. See also: gsp , xsp . gsp gsp : number. Ground speed, in pixels per second. Prefer using speed instead, since gsp is only meaningful if the player is touching the ground. See also: speed . xsp xsp : number. Horizontal speed, in pixels per second (useful while midair). Prefer using speed instead. See also: speed . ysp ysp : number. Vertical speed, in pixels per second. angle angle : number. The angle of the player, in degrees. The same as transform.angle . See also: slope , transform . slope slope : number, read-only. The angle detected by the physics system, in degrees. Unlike angle , slope is read-only and does not feature any smoothing for visual aesthetics. Its purpose is to be a helper for physics calculations. See also: angle . Available since: Open Surge 0.5.2 width width : number, read-only. The width of the player sprite, in pixels. See also: height . height height : number, read-only. The height of the player sprite, in pixels. See also: width . hflip hflip : boolean. Used to horizontally flip the sprite of the player relative to its direction . Defaults to false . Changing this flag does not change the direction of the player in any way. It only changes the way the sprite is rendered. Also, reading this flag alone does not tell you whether the sprite is facing left or right. Use it in addition to the direction of the player for that. See also: direction , vflip . Available since: Open Surge 0.6.1 Example // make the sprite appear in accordance with player.direction player . hflip = false ; // make the sprite appear flipped relative to player.direction player . hflip = true ; // make the sprite appear facing right, regardless of player.direction player . hflip = ( player . direction < 0 ); // make the sprite appear facing left, regardless of player.direction player . hflip = ( player . direction > 0 ); // spriteDirection is analogous to player.direction spriteDirection = player . direction * ( player . hflip ? - 1 : 1 ); // let's check if the sprite is facing right or left isFacingRight = ( spriteDirection > 0 ); isFacingLeft = ( spriteDirection < 0 ); vflip vflip : boolean. Used to vertically flip the sprite of the player. Defaults to false . See also: hflip . Available since: Open Surge 0.6.1 Functions bounce bounce(hazard | null) Makes the player bounce after smashing a hazard. The trajectory of the movement will be computed according to the position of the hazard. If no hazard is present, you may pass null as the argument. Arguments hazard : Actor object. The hazard. Example using SurgeEngine.Player ; using SurgeEngine.Actor ; using SurgeEngine.Collisions.CollisionBox ; object \"Shield Box\" is \"entity\" { actor = Actor ( \"Shield Box\" ); shieldCollider = CollisionBox ( 32 , 32 ); state \"main\" { player = Player . active ; if ( player . attacking ) { if ( player . collider . collidesWith ( shieldCollider )) { if ( player . midair ) player . bounce ( actor ); player . shield = \"fire\" ; destroy (); } } } } bounceBack bounceBack(hazard) Makes the player bounce after smashing a hazard. If the player comes at the hazard from below, the player is thrown downwards. If not, the player is thrown upwards. The hazard parameter is mandatory. Arguments hazard : Actor object. The hazard. getHit getHit(hazard | null) Makes the player get hit. Call it whenever the player gets hit by a hazard. The hit movement will be calculated according to the position of the hazard. If no hazard is present, you may pass null as the argument. Arguments hazard : Actor object. The hazard. See also: hit . kill kill() Kills the player. breathe breathe() Makes the player breathe (underwater only). restore restore() Restores the player to a vulnerable state. Available since: Open Surge 0.6.1 springify springify() Activates the \"springing\" activity. See also: restore . roll roll() Makes the player roll. hlock hlock(seconds) Locks the horizontal controls of the player for the specified time. Left and right input will be ignored during that time. See also: hlockTime . Arguments seconds : number. How long the horizontal controls of the player will stay locked? This usually should be set to a value no higher than 0.5 . Note: since Open Surge 0.6.1, the locking will not take place if the player is midair. focus focus() Focuses on the player. The focused player is controlled by the user. Only one player has focus at any given time. See also: hasFocus , focusable , Player.active . Returns Returns true on success, false otherwise. hasFocus hasFocus() Does the player have focus? See also: focus , focusable , Player.active . Returns Returns true if the player has focus, false otherwise. moveBy moveBy(dx, dy) Moves the player by a ( dx , dy ) offset after the physics update of the current framestep. This is similar to calling player.transform.translateBy(dx, dy) in lateUpdate() . See also: lateUpdate , translateBy . Available since: Open Surge 0.6.1 Arguments dx : number. Horizontal offset in pixels. dy : number. Vertical offset in pixels. Example // Let's compare player.moveBy() to // player.transform.translateBy() dx = 5 ; dy = 0 ; // this moves the player AFTER the physics update player . moveBy ( dx , dy ); // this moves the player BEFORE the physics update // (immediately), unless you call it in lateUpdate() player . transform . translateBy ( dx , dy ); move move(offset) Moves the player by the given offset after the physics update of the current framestep. Calling player.move(offset) is equivalent to calling player.moveBy(offset.x, offset.y) . See also: moveBy . Available since: Open Surge 0.6.1 Arguments offset : Vector2 object. Offset vector. transformInto player.transformInto(characterName) Transforms the player into the character named characterName . The transformation succeeds only if there is such a character. Available since: Open Surge 0.6.1 Arguments characterName : string. The name of a character, as defined in a .chr file. Returns Returns true if the transformation is successful. Transforming a player into itself is considered successful, but nothing happens in this case. // this player will become Surge player . transformInto ( \"Surge\" ); // this player will become Tux player . transformInto ( \"Tux\" ); // the following transformation will fail: if (! player . transformInto ( \"non-existent-character\" )) Console . print ( \"No transformation took place!\" ); // After a successful transformation: // - player.name will change; // - player.id will not change!","title":"Player"},{"location":"engine/player/#player","text":"The Player object is used to control a specific player/character. Player objects are tagged player . Note: in Open Surge, companion objects can be used to give new abilities to players. Companion objects must be indicated in the character definition files (.chr) and are implemented as regular scripts. The engine will automatically spawn the companions as children of the appropriate Player objects. Example object \"Display player name\" is \"companion\" { player = parent ; // since this object is configured as a // companion, parent is the reference // to the appropriate Player object state \"main\" { Console . print ( \"I am a companion of \" + player . name ); } }","title":"Player"},{"location":"engine/player/#global","text":"","title":"Global"},{"location":"engine/player/#player_1","text":"Player(playerName) Gets the Player object associated with a character in the level. If a player with the specified name doesn't exist in the level, there will be an error. See also: exists . Arguments playerName : string. The name of a character, as defined in a .chr file stored in the characters/ folder. Returns A Player object. Example using SurgeEngine.Player ; // Gives Surge 1 collectible each second // Just place it in your level object \"Collectible Giver\" is \"entity\" , \"awake\" { player = Player ( \"Surge\" ); state \"main\" { if ( timeout ( 1 )) state = \"give collectible\" ; } state \"give collectible\" { player . collectibles = player . collectibles + 1 ; state = \"main\" ; } }","title":"Player"},{"location":"engine/player/#playerget","text":"Player[i] Gets a Player object by its sequence number, as defined in the players entry of the level file. See also: count . Arguments i : number. An integer between 0 and Player.count - 1 , inclusive. Returns A Player object.","title":"Player.get"},{"location":"engine/player/#playerexists","text":"Player.exists(playerName) Checks if a player named playerName exists in the level. Arguments playerName : string. The name of a character. Returns Returns true if such a player exists in the level.","title":"Player.exists"},{"location":"engine/player/#playeractive","text":"Player.active : Player object. The player currently in focus. See also: focus , hasFocus , focusable . Example using SurgeEngine.Player ; // Tells the name of the active player // Just place it in the level object \"Who am I\" is \"entity\" , \"awake\" { state \"main\" { player = Player . active ; Console . print ( \"I am \" + player . name ); destroy (); } }","title":"Player.active"},{"location":"engine/player/#playercount","text":"Player.count : number, read-only. The number of players in the level.","title":"Player.count"},{"location":"engine/player/#playerinitiallives","text":"Player.initialLives : number, read-only. The initial number of lives set by the engine.","title":"Player.initialLives"},{"location":"engine/player/#properties","text":"","title":"Properties"},{"location":"engine/player/#id","text":"id : number, read-only. A number that uniquely identifies the player in the Level. See also: name . Available since: Open Surge 0.6.1","title":"id"},{"location":"engine/player/#name","text":"name : string, read-only. The name of the character. See also: id .","title":"name"},{"location":"engine/player/#direction","text":"direction : number, read-only. This number will be +1 if the player is facing right, or -1 if facing left. See also: hflip . Example // let's check if the player is facing right or left isFacingRight = ( player . direction > 0 ); isFacingLeft = ( player . direction < 0 );","title":"direction"},{"location":"engine/player/#input","text":"input : Input object, read-only. Reference to the Input object of the Player. Example using SurgeEngine.Player ; object \"Application\" { state \"main\" { player = Player . active ; if ( player . input . buttonDown ( \"right\" )) Console . print ( \"Player is holding right\" ); } }","title":"input"},{"location":"engine/player/#animation","text":"animation : Animation object, read-only. Reference to the Animation object of the Player. See also: anim .","title":"animation"},{"location":"engine/player/#anim","text":"anim : number. A shortcut to animation.id : an integer corresponding to the current animation number. See also: animation , id .","title":"anim"},{"location":"engine/player/#anchor","text":"anchor : Vector2 object. A shortcut to animation.anchor . See also: anchor . Available since: Open Surge 0.6.0","title":"anchor"},{"location":"engine/player/#hotspot","text":"hotSpot : Vector2 object. A shortcut to animation.hotSpot . See also: hotSpot . Available since: Open Surge 0.6.0. Note: in versions prior to 0.6.0, you may get the hot spot using the Animation object.","title":"hotSpot"},{"location":"engine/player/#actionspot","text":"actionSpot : Vector2 object. A shortcut to animation.actionSpot . See also: actionSpot . Available since: Open Surge 0.6.0","title":"actionSpot"},{"location":"engine/player/#actionoffset","text":"actionOffset : Vector2 object, read-only. A shortcut to animation.actionOffset . See also: actionOffset . Available since: Open Surge 0.6.0","title":"actionOffset"},{"location":"engine/player/#attacking","text":"attacking : boolean, read-only. Is the player attacking, i.e., jumping, rolling, charging or invincible? This flag will be modified if the player is aggressive or inoffensive. See also: aggressive , inoffensive .","title":"attacking"},{"location":"engine/player/#midair","text":"midair : boolean, read-only. Is the player midair?","title":"midair"},{"location":"engine/player/#stopped","text":"stopped : boolean, read-only. Is the player stopped?","title":"stopped"},{"location":"engine/player/#walking","text":"walking : boolean, read-only. Is the player walking?","title":"walking"},{"location":"engine/player/#running","text":"running : boolean, read-only. Is the player running?","title":"running"},{"location":"engine/player/#jumping","text":"jumping : boolean, read-only. Is the player jumping?","title":"jumping"},{"location":"engine/player/#springing","text":"springing : boolean, read-only. Is the player playing the \"springing\" animation, displayed just after hitting a spring?","title":"springing"},{"location":"engine/player/#braking","text":"braking : boolean, read-only. Is the player braking?","title":"braking"},{"location":"engine/player/#balancing","text":"balancing : boolean, read-only. Is the player balancing on a ledge?","title":"balancing"},{"location":"engine/player/#waiting","text":"waiting : boolean, read-only. Is the player waiting? (happens after remaining stopped for a few seconds)","title":"waiting"},{"location":"engine/player/#rolling","text":"rolling : boolean, read-only. Is the player rolling?","title":"rolling"},{"location":"engine/player/#charging","text":"charging : boolean, read-only. Is the player charging a rolling movement?","title":"charging"},{"location":"engine/player/#pushing","text":"pushing : boolean, read-only. Is the player pushing a wall?","title":"pushing"},{"location":"engine/player/#hit","text":"hit : boolean, read-only. Is the player getting hit (i.e., losing collectibles or a shield)? See also: getHit .","title":"hit"},{"location":"engine/player/#blinking","text":"blinking : boolean, read-only. Is the player blinking? (happens just after getting hit)","title":"blinking"},{"location":"engine/player/#dying","text":"dying : boolean, read-only. Is the player dying or drowning?","title":"dying"},{"location":"engine/player/#drowning","text":"drowning : boolean, read-only. Is the player drowning (i.e., dying underwater)? See also: underwater , dying .","title":"drowning"},{"location":"engine/player/#breathing","text":"breathing : boolean, read-only. Is the player breathing an air bubble that is underwater? See also: underwater , breathTime .","title":"breathing"},{"location":"engine/player/#crouchingdown","text":"crouchingDown : boolean, read-only. Is the player crouching down?","title":"crouchingDown"},{"location":"engine/player/#lookingup","text":"lookingUp : boolean, read-only. Is the player looking up?","title":"lookingUp"},{"location":"engine/player/#winning","text":"winning : boolean, read-only. Is the player displaying the \"winning\" animation (after clearing a level)?","title":"winning"},{"location":"engine/player/#underwater","text":"underwater : boolean, read-only. Is the player underwater? Players are considered to be underwater if they are below the water level or if their forciblyUnderwater flag is set to true . See also: secondsToDrown , drowning , breathing , breathTime , forciblyUnderwater , forciblyOutOfWater , waterlevel .","title":"underwater"},{"location":"engine/player/#secondstodrown","text":"secondsToDrown : number, read-only. The number of seconds to drown, if underwater. See also: underwater , drowning , breathTime .","title":"secondsToDrown"},{"location":"engine/player/#topspeed","text":"topspeed : number, read-only. The maximum speed that the player can reach when running naturally, without rolling and with no external forces applied. Given in pixels per second. See also: capspeed .","title":"topspeed"},{"location":"engine/player/#capspeed","text":"capspeed : number, read-only. The maximum speed that the player can reach by normal means (e.g., rolling downhill), not considering external forces. Given in pixels per second. See also: topspeed . Available since: Open Surge 0.6.1","title":"capspeed"},{"location":"engine/player/#hlocktime","text":"hlockTime : number, read-only. The time, in seconds, in which the player will not respond to horizontal input when on the ground. Defaults to zero. See also: hlock . Available since: Open Surge 0.6.1","title":"hlockTime"},{"location":"engine/player/#transform","text":"transform : Transform object, read-only. The transform of the Player.","title":"transform"},{"location":"engine/player/#collider","text":"collider : Collider object, read-only. A collider associated with this Player.","title":"collider"},{"location":"engine/player/#shield","text":"shield : string | null . One of the following: \"shield\" , \"fire\" , \"thunder\" , \"water\" , \"acid\" , \"wind\" or null (if there is no shield). See also: invulnerable .","title":"shield"},{"location":"engine/player/#invincible","text":"invincible : boolean. Used to make the player invincible. Defaults to false .","title":"invincible"},{"location":"engine/player/#turbo","text":"turbo : boolean. Turbocharged mode (increases player speed). Defaults to false .","title":"turbo"},{"location":"engine/player/#frozen","text":"frozen : boolean. Disable/enable player movement. Defaults to false .","title":"frozen"},{"location":"engine/player/#aggressive","text":"aggressive : boolean. If set to true , the attacking flag will be true regardless of the state of the player. The player will be able to hit the baddies just by touching them. Defaults to false . See also: attacking , inoffensive . Available since: Open Surge 0.5.1","title":"aggressive"},{"location":"engine/player/#inoffensive","text":"inoffensive : boolean. If set to true , the attacking flag will be false regardless of the state of the player. The player will be vulnerable to damage even if jumping, rolling or charging. Defaults to false . Note: if the player is simultaneously aggressive and inoffensive, the aggressive behavior prevails. See also: attacking , aggressive . Available since: Open Surge 0.6.1","title":"inoffensive"},{"location":"engine/player/#invulnerable","text":"invulnerable : boolean. If set to true , the player will be invulnerable to damage. It's like having an invisible shield that is permanent. The player may still be killed if crushed, by falling into a pit, by drowning, or by calling kill . Available since: Open Surge 0.6.1","title":"invulnerable"},{"location":"engine/player/#immortal","text":"immortal : boolean. If an immortal player appears to be killed, it will appear to be ressurrected on its spawn point without losing a life . See also: lives . Available since: Open Surge 0.6.1","title":"immortal"},{"location":"engine/player/#secondary","text":"secondary : boolean. A secondary player plays a secondary role and interacts with items in different ways. It cannot smash item boxes, activate goal signs, etc. This flag is best used with AI-controlled players. Defaults to false . Available since: Open Surge 0.6.1","title":"secondary"},{"location":"engine/player/#focusable","text":"focusable : boolean. A focusable player can receive focus. Defaults to true . See also: focus , hasFocus , Player.active . Available since: Open Surge 0.6.1 Note: if only a single player exists in the level, then that player will have focus regardless of the value of this flag.","title":"focusable"},{"location":"engine/player/#breathtime","text":"breathTime : number. The maximum number of seconds the player can remain underwater without breathing. See also: underwater , secondsToDrown .","title":"breathTime"},{"location":"engine/player/#forciblyunderwater","text":"forciblyUnderwater : boolean. If set to true , the underwater flag will be true regardless of the water level . If set to false , the underwater flag will be true only if the player is below the water level. Defaults to false . See also: underwater , waterlevel , forciblyOutOfWater . Available since: Open Surge 0.6.1","title":"forciblyUnderwater"},{"location":"engine/player/#forciblyoutofwater","text":"If set to true , the underwater mechanics will be disabled, even if the player is below the water level . If forciblyUnderwater is also true , this flag will do nothing. Defaults to false . See also: underwater , waterlevel , forciblyUnderwater . Available since: Open Surge 0.6.1","title":"forciblyOutOfWater"},{"location":"engine/player/#layer","text":"layer : string. The current layer of the player. One of the following: \"green\" , \"yellow\" , \"default\" . This property tells you which bricks will be sensed, depending on their layer.","title":"layer"},{"location":"engine/player/#visible","text":"visible : boolean. Should the player sprite be rendered? Defaults to true .","title":"visible"},{"location":"engine/player/#collectibles","text":"collectibles : number. The number of collectibles, an integer shared between all player objects.","title":"collectibles"},{"location":"engine/player/#lives","text":"lives : number. The number of lives, an integer shared between all player objects.","title":"lives"},{"location":"engine/player/#score","text":"score : number. The score of the player, an integer value shared between all player objects.","title":"score"},{"location":"engine/player/#speed","text":"speed : number. The speed of the player, in pixels per second. This will be mapped automatically to gsp or xsp , depending on whether the player is touching the ground or not. See also: gsp , xsp .","title":"speed"},{"location":"engine/player/#gsp","text":"gsp : number. Ground speed, in pixels per second. Prefer using speed instead, since gsp is only meaningful if the player is touching the ground. See also: speed .","title":"gsp"},{"location":"engine/player/#xsp","text":"xsp : number. Horizontal speed, in pixels per second (useful while midair). Prefer using speed instead. See also: speed .","title":"xsp"},{"location":"engine/player/#ysp","text":"ysp : number. Vertical speed, in pixels per second.","title":"ysp"},{"location":"engine/player/#angle","text":"angle : number. The angle of the player, in degrees. The same as transform.angle . See also: slope , transform .","title":"angle"},{"location":"engine/player/#slope","text":"slope : number, read-only. The angle detected by the physics system, in degrees. Unlike angle , slope is read-only and does not feature any smoothing for visual aesthetics. Its purpose is to be a helper for physics calculations. See also: angle . Available since: Open Surge 0.5.2","title":"slope"},{"location":"engine/player/#width","text":"width : number, read-only. The width of the player sprite, in pixels. See also: height .","title":"width"},{"location":"engine/player/#height","text":"height : number, read-only. The height of the player sprite, in pixels. See also: width .","title":"height"},{"location":"engine/player/#hflip","text":"hflip : boolean. Used to horizontally flip the sprite of the player relative to its direction . Defaults to false . Changing this flag does not change the direction of the player in any way. It only changes the way the sprite is rendered. Also, reading this flag alone does not tell you whether the sprite is facing left or right. Use it in addition to the direction of the player for that. See also: direction , vflip . Available since: Open Surge 0.6.1 Example // make the sprite appear in accordance with player.direction player . hflip = false ; // make the sprite appear flipped relative to player.direction player . hflip = true ; // make the sprite appear facing right, regardless of player.direction player . hflip = ( player . direction < 0 ); // make the sprite appear facing left, regardless of player.direction player . hflip = ( player . direction > 0 ); // spriteDirection is analogous to player.direction spriteDirection = player . direction * ( player . hflip ? - 1 : 1 ); // let's check if the sprite is facing right or left isFacingRight = ( spriteDirection > 0 ); isFacingLeft = ( spriteDirection < 0 );","title":"hflip"},{"location":"engine/player/#vflip","text":"vflip : boolean. Used to vertically flip the sprite of the player. Defaults to false . See also: hflip . Available since: Open Surge 0.6.1","title":"vflip"},{"location":"engine/player/#functions","text":"","title":"Functions"},{"location":"engine/player/#bounce","text":"bounce(hazard | null) Makes the player bounce after smashing a hazard. The trajectory of the movement will be computed according to the position of the hazard. If no hazard is present, you may pass null as the argument. Arguments hazard : Actor object. The hazard. Example using SurgeEngine.Player ; using SurgeEngine.Actor ; using SurgeEngine.Collisions.CollisionBox ; object \"Shield Box\" is \"entity\" { actor = Actor ( \"Shield Box\" ); shieldCollider = CollisionBox ( 32 , 32 ); state \"main\" { player = Player . active ; if ( player . attacking ) { if ( player . collider . collidesWith ( shieldCollider )) { if ( player . midair ) player . bounce ( actor ); player . shield = \"fire\" ; destroy (); } } } }","title":"bounce"},{"location":"engine/player/#bounceback","text":"bounceBack(hazard) Makes the player bounce after smashing a hazard. If the player comes at the hazard from below, the player is thrown downwards. If not, the player is thrown upwards. The hazard parameter is mandatory. Arguments hazard : Actor object. The hazard.","title":"bounceBack"},{"location":"engine/player/#gethit","text":"getHit(hazard | null) Makes the player get hit. Call it whenever the player gets hit by a hazard. The hit movement will be calculated according to the position of the hazard. If no hazard is present, you may pass null as the argument. Arguments hazard : Actor object. The hazard. See also: hit .","title":"getHit"},{"location":"engine/player/#kill","text":"kill() Kills the player.","title":"kill"},{"location":"engine/player/#breathe","text":"breathe() Makes the player breathe (underwater only).","title":"breathe"},{"location":"engine/player/#restore","text":"restore() Restores the player to a vulnerable state. Available since: Open Surge 0.6.1","title":"restore"},{"location":"engine/player/#springify","text":"springify() Activates the \"springing\" activity. See also: restore .","title":"springify"},{"location":"engine/player/#roll","text":"roll() Makes the player roll.","title":"roll"},{"location":"engine/player/#hlock","text":"hlock(seconds) Locks the horizontal controls of the player for the specified time. Left and right input will be ignored during that time. See also: hlockTime . Arguments seconds : number. How long the horizontal controls of the player will stay locked? This usually should be set to a value no higher than 0.5 . Note: since Open Surge 0.6.1, the locking will not take place if the player is midair.","title":"hlock"},{"location":"engine/player/#focus","text":"focus() Focuses on the player. The focused player is controlled by the user. Only one player has focus at any given time. See also: hasFocus , focusable , Player.active . Returns Returns true on success, false otherwise.","title":"focus"},{"location":"engine/player/#hasfocus","text":"hasFocus() Does the player have focus? See also: focus , focusable , Player.active . Returns Returns true if the player has focus, false otherwise.","title":"hasFocus"},{"location":"engine/player/#moveby","text":"moveBy(dx, dy) Moves the player by a ( dx , dy ) offset after the physics update of the current framestep. This is similar to calling player.transform.translateBy(dx, dy) in lateUpdate() . See also: lateUpdate , translateBy . Available since: Open Surge 0.6.1 Arguments dx : number. Horizontal offset in pixels. dy : number. Vertical offset in pixels. Example // Let's compare player.moveBy() to // player.transform.translateBy() dx = 5 ; dy = 0 ; // this moves the player AFTER the physics update player . moveBy ( dx , dy ); // this moves the player BEFORE the physics update // (immediately), unless you call it in lateUpdate() player . transform . translateBy ( dx , dy );","title":"moveBy"},{"location":"engine/player/#move","text":"move(offset) Moves the player by the given offset after the physics update of the current framestep. Calling player.move(offset) is equivalent to calling player.moveBy(offset.x, offset.y) . See also: moveBy . Available since: Open Surge 0.6.1 Arguments offset : Vector2 object. Offset vector.","title":"move"},{"location":"engine/player/#transforminto","text":"player.transformInto(characterName) Transforms the player into the character named characterName . The transformation succeeds only if there is such a character. Available since: Open Surge 0.6.1 Arguments characterName : string. The name of a character, as defined in a .chr file. Returns Returns true if the transformation is successful. Transforming a player into itself is considered successful, but nothing happens in this case. // this player will become Surge player . transformInto ( \"Surge\" ); // this player will become Tux player . transformInto ( \"Tux\" ); // the following transformation will fail: if (! player . transformInto ( \"non-existent-character\" )) Console . print ( \"No transformation took place!\" ); // After a successful transformation: // - player.name will change; // - player.id will not change!","title":"transformInto"},{"location":"engine/prefs/","text":"Prefs Prefs is a SurgeEngine component used to save/load data to/from the disk (permanent storage). Prefs is a (key, value) storage that works like a Dictionary , but its data can be persisted between game sessions. Example using SurgeEngine.Prefs ; // Run the Application multiple times and see // how the counter increments object \"Application\" { state \"main\" { Prefs [ \"counter\" ] += 1 ; Console . print ( \"counter: \" + Prefs [ \"counter\" ]); state = \"idle\" ; } state \"idle\" { } fun constructor () { if (! Prefs . has ( \"counter\" )) Prefs [ \"counter\" ] = 0 ; } } Functions get get(key) Gets the value of the specified key. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments key : string. The key must always be a string. Returns Returns the value associated with the specified key, or null if there is no such value. set set(key, value) Sets the value of the specified key. Instead of calling set() directly, you may equivalently use the [ ] operator. Arguments key : string. The key must always be a string. value : any type. The value you want to store. clear clear() Removes all entries from Prefs. Use this very carefully, because data will be lost. delete delete(key) Deletes the entry having the specified key. Arguments key : string. The key of the entry to be removed. has has(key) Checks if a specific entry exists. Arguments key : string. The key of the entry. Returns Returns true if the specified entry exists, false otherwise. save save() Writes the data to secondary storage. The data isn't saved immediately after you set an entry, but it is saved on key moments. Since the data is persisted automatically, normally you don't need to call this.","title":"Prefs"},{"location":"engine/prefs/#prefs","text":"Prefs is a SurgeEngine component used to save/load data to/from the disk (permanent storage). Prefs is a (key, value) storage that works like a Dictionary , but its data can be persisted between game sessions. Example using SurgeEngine.Prefs ; // Run the Application multiple times and see // how the counter increments object \"Application\" { state \"main\" { Prefs [ \"counter\" ] += 1 ; Console . print ( \"counter: \" + Prefs [ \"counter\" ]); state = \"idle\" ; } state \"idle\" { } fun constructor () { if (! Prefs . has ( \"counter\" )) Prefs [ \"counter\" ] = 0 ; } }","title":"Prefs"},{"location":"engine/prefs/#functions","text":"","title":"Functions"},{"location":"engine/prefs/#get","text":"get(key) Gets the value of the specified key. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments key : string. The key must always be a string. Returns Returns the value associated with the specified key, or null if there is no such value.","title":"get"},{"location":"engine/prefs/#set","text":"set(key, value) Sets the value of the specified key. Instead of calling set() directly, you may equivalently use the [ ] operator. Arguments key : string. The key must always be a string. value : any type. The value you want to store.","title":"set"},{"location":"engine/prefs/#clear","text":"clear() Removes all entries from Prefs. Use this very carefully, because data will be lost.","title":"clear"},{"location":"engine/prefs/#delete","text":"delete(key) Deletes the entry having the specified key. Arguments key : string. The key of the entry to be removed.","title":"delete"},{"location":"engine/prefs/#has","text":"has(key) Checks if a specific entry exists. Arguments key : string. The key of the entry. Returns Returns true if the specified entry exists, false otherwise.","title":"has"},{"location":"engine/prefs/#save","text":"save() Writes the data to secondary storage. The data isn't saved immediately after you set an entry, but it is saved on key moments. Since the data is persisted automatically, normally you don't need to call this.","title":"save"},{"location":"engine/screen/","text":"Screen Screen settings. The screen represents the backbuffer, i.e., the texture in which things are drawn. Example // display the size of the screen using SurgeEngine.Video.Screen ; object \"Application\" { width = Screen . width ; height = Screen . height ; state \"main\" { Console . print ( width + \"x\" + height ); state = \"done\" ; } state \"done\" { } } Properties width width : number, read-only. The width of the screen, in pixels. height height : number, read-only. The height of the screen, in pixels.","title":"Screen"},{"location":"engine/screen/#screen","text":"Screen settings. The screen represents the backbuffer, i.e., the texture in which things are drawn. Example // display the size of the screen using SurgeEngine.Video.Screen ; object \"Application\" { width = Screen . width ; height = Screen . height ; state \"main\" { Console . print ( width + \"x\" + height ); state = \"done\" ; } state \"done\" { } }","title":"Screen"},{"location":"engine/screen/#properties","text":"","title":"Properties"},{"location":"engine/screen/#width","text":"width : number, read-only. The width of the screen, in pixels.","title":"width"},{"location":"engine/screen/#height","text":"height : number, read-only. The height of the screen, in pixels.","title":"height"},{"location":"engine/sensor/","text":"Sensor A Sensor is used to detect collisions with bricks. Due to performance optimizations, passable bricks (or bricks that are too far off camera) can't be sensed. Example using SurgeEngine.Actor ; using SurgeEngine.Collisions.Sensor ; object \"SensorToy\" is \"entity\" { actor = Actor ( \"SensorToy\" ); sensor = Sensor ( 0 , - 25 , 1 , 50 ); // a vertical sensor state \"main\" { if ( sensor . status != null ) Console . print ( \"Got a brick of type \" + sensor . status ); } fun constructor () { sensor . visible = true ; } } Factory Sensor Collisions.Sensor(x, y, width, height) Spawns a new Sensor with the specified dimensions and having its top-left corner located at position ( x , y ) relative to the parent object. A Sensor is either a vertical or a horizontal bar that is 1-pixel thin. Both width and height must be positive integers, and at least one of them must be equal to 1. Arguments x : number. The x-position of the top-left corner of the sensor, relative to the parent object. y : number. The y-position of the top-left corner of the sensor, relative to the parent object. width : number. The width of the sensor, in pixels. Must be a positive integer. height : number. The height of the sensor, in pixels. Must be a positive integer. Returns A Sensor with the specified parameters. Properties status status : string | null , read-only. The type of the brick colliding with the sensor (either \"solid\" or \"cloud\" ). If the sensor isn't colliding with a brick, or if it's disabled, its status will be null . visible visible : boolean. Should the sensor be rendered? Useful for debugging. Defaults to false . enabled enabled : boolean. Indicates whether the sensor is enabled or not. Defaults to true . layer layer : string. The layer of this sensor. This property assumes one of the following values: \"default\" , \"green\" or \"yellow\" . If it's set to \"default\" , then all non-passable bricks and brick-like objects are sensed. If it's set to \"green\" , then all non-passable bricks and brick-like objects are sensed, except the ones in the yellow layer. Conversely, if it's set to \"yellow\" , then all non-passable bricks and brick-like objects are sensed, except the ones in the green layer. Available since: Open Surge 0.6.1","title":"Sensor"},{"location":"engine/sensor/#sensor","text":"A Sensor is used to detect collisions with bricks. Due to performance optimizations, passable bricks (or bricks that are too far off camera) can't be sensed. Example using SurgeEngine.Actor ; using SurgeEngine.Collisions.Sensor ; object \"SensorToy\" is \"entity\" { actor = Actor ( \"SensorToy\" ); sensor = Sensor ( 0 , - 25 , 1 , 50 ); // a vertical sensor state \"main\" { if ( sensor . status != null ) Console . print ( \"Got a brick of type \" + sensor . status ); } fun constructor () { sensor . visible = true ; } }","title":"Sensor"},{"location":"engine/sensor/#factory","text":"","title":"Factory"},{"location":"engine/sensor/#sensor_1","text":"Collisions.Sensor(x, y, width, height) Spawns a new Sensor with the specified dimensions and having its top-left corner located at position ( x , y ) relative to the parent object. A Sensor is either a vertical or a horizontal bar that is 1-pixel thin. Both width and height must be positive integers, and at least one of them must be equal to 1. Arguments x : number. The x-position of the top-left corner of the sensor, relative to the parent object. y : number. The y-position of the top-left corner of the sensor, relative to the parent object. width : number. The width of the sensor, in pixels. Must be a positive integer. height : number. The height of the sensor, in pixels. Must be a positive integer. Returns A Sensor with the specified parameters.","title":"Sensor"},{"location":"engine/sensor/#properties","text":"","title":"Properties"},{"location":"engine/sensor/#status","text":"status : string | null , read-only. The type of the brick colliding with the sensor (either \"solid\" or \"cloud\" ). If the sensor isn't colliding with a brick, or if it's disabled, its status will be null .","title":"status"},{"location":"engine/sensor/#visible","text":"visible : boolean. Should the sensor be rendered? Useful for debugging. Defaults to false .","title":"visible"},{"location":"engine/sensor/#enabled","text":"enabled : boolean. Indicates whether the sensor is enabled or not. Defaults to true .","title":"enabled"},{"location":"engine/sensor/#layer","text":"layer : string. The layer of this sensor. This property assumes one of the following values: \"default\" , \"green\" or \"yellow\" . If it's set to \"default\" , then all non-passable bricks and brick-like objects are sensed. If it's set to \"green\" , then all non-passable bricks and brick-like objects are sensed, except the ones in the yellow layer. Conversely, if it's set to \"yellow\" , then all non-passable bricks and brick-like objects are sensed, except the ones in the green layer. Available since: Open Surge 0.6.1","title":"layer"},{"location":"engine/sound/","text":"Sound The Sound object lets you play samples, which are short sounds like: jump, brake, select, hit, etc. Sounds are loaded entirely in the memory; therefore, this object is meant to be used only with samples. If you need to play longer things like music, consider using Music instead. Example using SurgeEngine.Audio.Sound ; // will play a sound every 5 seconds object \"SoundTest\" { sound = Sound ( \"samples/jump.wav\" ); state \"main\" { sound . play (); state = \"wait\" ; } state \"wait\" { if ( timeout ( 5.0 )) state = \"main\" ; } } Factory Sound Audio.Sound(path) Creates a Sound object associated with a certain file. Arguments path : string. The path of the sound - usually a file in the samples/ folder. Returns A Sound object. Properties playing playing : boolean, read-only. Will be true if the sound is playing. volume volume : number. The volume of the sound, a value between 0.0 and 1.0, inclusive (zero means silence). Functions play play() Plays the sound. stop stop() Stops the sound.","title":"Sound"},{"location":"engine/sound/#sound","text":"The Sound object lets you play samples, which are short sounds like: jump, brake, select, hit, etc. Sounds are loaded entirely in the memory; therefore, this object is meant to be used only with samples. If you need to play longer things like music, consider using Music instead. Example using SurgeEngine.Audio.Sound ; // will play a sound every 5 seconds object \"SoundTest\" { sound = Sound ( \"samples/jump.wav\" ); state \"main\" { sound . play (); state = \"wait\" ; } state \"wait\" { if ( timeout ( 5.0 )) state = \"main\" ; } }","title":"Sound"},{"location":"engine/sound/#factory","text":"","title":"Factory"},{"location":"engine/sound/#sound_1","text":"Audio.Sound(path) Creates a Sound object associated with a certain file. Arguments path : string. The path of the sound - usually a file in the samples/ folder. Returns A Sound object.","title":"Sound"},{"location":"engine/sound/#properties","text":"","title":"Properties"},{"location":"engine/sound/#playing","text":"playing : boolean, read-only. Will be true if the sound is playing.","title":"playing"},{"location":"engine/sound/#volume","text":"volume : number. The volume of the sound, a value between 0.0 and 1.0, inclusive (zero means silence).","title":"volume"},{"location":"engine/sound/#functions","text":"","title":"Functions"},{"location":"engine/sound/#play","text":"play() Plays the sound.","title":"play"},{"location":"engine/sound/#stop","text":"stop() Stops the sound.","title":"stop"},{"location":"engine/surgeengine/","text":"SurgeEngine The SurgeEngine plugin is the interface between SurgeScript (scripting language) and Open Surge (game engine). Example using SurgeEngine ; // Open Surge version object \"Application\" { state \"main\" { Console . print ( SurgeEngine . version ); state = \"blank\" ; } state \"blank\" { } } Properties version version : string, read-only. Version of the Open Surge Engine. mobile mobile : boolean, read-only. Whether or not the engine has been launched in mobile mode. The user may be playing on a mobile device or on a Desktop computer with the mobile mode enabled. Available since: Open Surge 0.6.1","title":"SurgeEngine"},{"location":"engine/surgeengine/#surgeengine","text":"The SurgeEngine plugin is the interface between SurgeScript (scripting language) and Open Surge (game engine). Example using SurgeEngine ; // Open Surge version object \"Application\" { state \"main\" { Console . print ( SurgeEngine . version ); state = \"blank\" ; } state \"blank\" { } }","title":"SurgeEngine"},{"location":"engine/surgeengine/#properties","text":"","title":"Properties"},{"location":"engine/surgeengine/#version","text":"version : string, read-only. Version of the Open Surge Engine.","title":"version"},{"location":"engine/surgeengine/#mobile","text":"mobile : boolean, read-only. Whether or not the engine has been launched in mobile mode. The user may be playing on a mobile device or on a Desktop computer with the mobile mode enabled. Available since: Open Surge 0.6.1","title":"mobile"},{"location":"engine/text/","text":"Text The Text object allows you to display custom texts in the game. The parent object is required to be an entity . Factory Text UI.Text(font) Spawns a new Text object with the given font name. If null is provided as the font name, then a default font will be used. Arguments font : string. The name of a font (defined in the fonts/ folder). Returns A Text object. Example using SurgeEngine.UI.Text ; using SurgeEngine.Transform ; using SurgeEngine.Player ; // Place this on your level to display // the name of the player object \"PlayerName\" is \"entity\" , \"awake\" { text = Text ( \"GoodNeighbors\" ); transform = Transform (); state \"main\" { // position the text player = Player . active ; transform . position = player . transform . position ; transform . translateBy ( 0 , - 50 ); // configure the text text . align = \"center\" ; text . text = player . name ; } } Properties text text : string. The text to be displayed. font font : string, read-only. The name of the font in use. size size : Vector2 object, read-only. The size, in pixels, of the rendered text. Available since: Open Surge 0.5.1 align align : string. The alignment of the text. One of the following: \"left\" , \"center\" , \"right\" . visible visible : boolean. Is the Text object visible? maxLength maxLength : number. The maximum number of characters to be displayed, ignoring tags and spaces. Available since: Open Surge 0.5.1 maxWidth maxWidth : number. The maximum width of the text, in pixels. Setting this value will enable wordwrap. zindex zindex : number. The zindex of the Text object. Defaults to 0.5. offset offset : Vector2 object. An (x,y) offset relative to the parent object. Defaults to zero.","title":"Text"},{"location":"engine/text/#text","text":"The Text object allows you to display custom texts in the game. The parent object is required to be an entity .","title":"Text"},{"location":"engine/text/#factory","text":"","title":"Factory"},{"location":"engine/text/#text_1","text":"UI.Text(font) Spawns a new Text object with the given font name. If null is provided as the font name, then a default font will be used. Arguments font : string. The name of a font (defined in the fonts/ folder). Returns A Text object. Example using SurgeEngine.UI.Text ; using SurgeEngine.Transform ; using SurgeEngine.Player ; // Place this on your level to display // the name of the player object \"PlayerName\" is \"entity\" , \"awake\" { text = Text ( \"GoodNeighbors\" ); transform = Transform (); state \"main\" { // position the text player = Player . active ; transform . position = player . transform . position ; transform . translateBy ( 0 , - 50 ); // configure the text text . align = \"center\" ; text . text = player . name ; } }","title":"Text"},{"location":"engine/text/#properties","text":"","title":"Properties"},{"location":"engine/text/#text_2","text":"text : string. The text to be displayed.","title":"text"},{"location":"engine/text/#font","text":"font : string, read-only. The name of the font in use.","title":"font"},{"location":"engine/text/#size","text":"size : Vector2 object, read-only. The size, in pixels, of the rendered text. Available since: Open Surge 0.5.1","title":"size"},{"location":"engine/text/#align","text":"align : string. The alignment of the text. One of the following: \"left\" , \"center\" , \"right\" .","title":"align"},{"location":"engine/text/#visible","text":"visible : boolean. Is the Text object visible?","title":"visible"},{"location":"engine/text/#maxlength","text":"maxLength : number. The maximum number of characters to be displayed, ignoring tags and spaces. Available since: Open Surge 0.5.1","title":"maxLength"},{"location":"engine/text/#maxwidth","text":"maxWidth : number. The maximum width of the text, in pixels. Setting this value will enable wordwrap.","title":"maxWidth"},{"location":"engine/text/#zindex","text":"zindex : number. The zindex of the Text object. Defaults to 0.5.","title":"zindex"},{"location":"engine/text/#offset","text":"offset : Vector2 object. An (x,y) offset relative to the parent object. Defaults to zero.","title":"offset"},{"location":"engine/transform/","text":"Transform Transform encapsulates a 2D Transform. It comes with functions for translating, rotating and scaling things - and it's very useful for games! Whenever you spawn a Transform on your object, you gain power to command its position, rotation and scale. The Transform component can only be spawned on entities . If an entity with a Transform component has any children, the transform of the children will be affected by the transform of their parent. Example: if you move an object, its children will be moved by the same amount. Factory Transform Transform() Spawns a Transform on the object. The object is required to be an entity . Returns A Transform object. Example using SurgeEngine.Actor ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // prints the position of this entity Console . print ( transform . position ); } } Properties position position : Vector2 object. The position of the object in world coordinates. Only use this property if you need to read the position of the object or to set it to a fixed value. If you need to move the entity, use translateBy instead. Example using SurgeEngine.Actor ; using SurgeEngine.Player ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // this will show the distance between // this entity and the active player player = Player . active ; Console . print ( distanceTo ( player )); } fun distanceTo ( obj ) { return transform . position . distanceTo ( obj . transform . position ); } } angle angle : number. The angle, in degrees, specifying the rotation of the object. Unless you need to read or to set the angle of the object to a pre-determined value, consider using rotate instead. localPosition localPosition : Vector2 object. The position of the object relative to the parent object. Only use this property if you need to read the position of the object or to set it to a fixed value. If you need to move the entity, use translateBy instead. localAngle localAngle : number. The angle, in degrees, relative to the angle of the parent object. Unless you need to read or to set the angle of the object to a pre-determined value, consider using rotate instead. localScale localScale : Vector2 object. The local scale of the object. A value of 1.0 in both axes means the default size. A value of 2.0, twice the default size, and so on. lossyScale lossyScale : Vector2 object, read-only. An approximation of the world scale of the object. It's not very accurate (the parent transform may be rotated and scaled), but it's useful. Available since: Open Surge 0.5.1 right right : Vector2 object, read-only. The right vector of the transform in world space. Unlike Vector2.right , this property considers the rotation of the transform. Available since: Open Surge 0.5.1 up up : Vector2 object, read-only. The up vector of the transform in world space. Unlike Vector2.up , this property considers the rotation of the transform. Available since: Open Surge 0.5.1 Functions translateBy translateBy(dx, dy) Translates (moves) the object by ( dx , dy ). Available since: Open Surge 0.5.1. See the note below. Arguments dx : number. Specifies how much to move the object in the x-axis. dy : number. Specifies how much to move the object in the y-axis. Example using SurgeEngine.Actor ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // move the entity at a speed of // 50 pixels/second, to the right transform . translateBy ( 50 * Time . delta , 0 ); // the command below would move it // at a speed of 30 pixels per FRAME //transform.translateBy(30, 0); // don't do this // since the framerate may vary across // different systems, it's advisable // to multiply the value by Time.delta // to make the behavior consistent. } } Note: in versions prior to 0.5.1, this function was called move . translate translate(delta) Translates the object by a delta vector. Arguments delta : Vector2 object. rotate rotate(deg) Rotates the object by deg degrees. Arguments deg : number. An angle in degrees. Example using SurgeEngine.Actor ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // rotate the entity at a speed of // 45 degrees per second transform . rotate ( 45 * Time . delta ); } } scaleBy scaleBy(sx, sy) Scales the object by horizontal and vertical factors sx and sy , respectively. Available since: Open Surge 0.6.1. Arguments sx : number. Horizontal scale factor. Value 1.0 means no change. sy : number. Vertical scale factor. Value 1.0 means no change. scale scale(resize) Scales the object by a resize vector. Available since: Open Surge 0.6.1. Arguments resize : Vector2 object. Vector2(1,1) means no change. lookAt lookAt(position) Rotates the transform so that its right vector points at the given position. Use this function to make your object look at some point in world space. Available since: Open Surge 0.5.1. See the note below. Arguments position : Vector2 object. A point in world space. Example using SurgeEngine.Actor ; using SurgeEngine.Player ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { player = Player . active ; transform . lookAt ( player . transform . position ); } } Note: in versions prior to 0.5.1, this function accepted a Transform parameter.","title":"Transform"},{"location":"engine/transform/#transform","text":"Transform encapsulates a 2D Transform. It comes with functions for translating, rotating and scaling things - and it's very useful for games! Whenever you spawn a Transform on your object, you gain power to command its position, rotation and scale. The Transform component can only be spawned on entities . If an entity with a Transform component has any children, the transform of the children will be affected by the transform of their parent. Example: if you move an object, its children will be moved by the same amount.","title":"Transform"},{"location":"engine/transform/#factory","text":"","title":"Factory"},{"location":"engine/transform/#transform_1","text":"Transform() Spawns a Transform on the object. The object is required to be an entity . Returns A Transform object. Example using SurgeEngine.Actor ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // prints the position of this entity Console . print ( transform . position ); } }","title":"Transform"},{"location":"engine/transform/#properties","text":"","title":"Properties"},{"location":"engine/transform/#position","text":"position : Vector2 object. The position of the object in world coordinates. Only use this property if you need to read the position of the object or to set it to a fixed value. If you need to move the entity, use translateBy instead. Example using SurgeEngine.Actor ; using SurgeEngine.Player ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // this will show the distance between // this entity and the active player player = Player . active ; Console . print ( distanceTo ( player )); } fun distanceTo ( obj ) { return transform . position . distanceTo ( obj . transform . position ); } }","title":"position"},{"location":"engine/transform/#angle","text":"angle : number. The angle, in degrees, specifying the rotation of the object. Unless you need to read or to set the angle of the object to a pre-determined value, consider using rotate instead.","title":"angle"},{"location":"engine/transform/#localposition","text":"localPosition : Vector2 object. The position of the object relative to the parent object. Only use this property if you need to read the position of the object or to set it to a fixed value. If you need to move the entity, use translateBy instead.","title":"localPosition"},{"location":"engine/transform/#localangle","text":"localAngle : number. The angle, in degrees, relative to the angle of the parent object. Unless you need to read or to set the angle of the object to a pre-determined value, consider using rotate instead.","title":"localAngle"},{"location":"engine/transform/#localscale","text":"localScale : Vector2 object. The local scale of the object. A value of 1.0 in both axes means the default size. A value of 2.0, twice the default size, and so on.","title":"localScale"},{"location":"engine/transform/#lossyscale","text":"lossyScale : Vector2 object, read-only. An approximation of the world scale of the object. It's not very accurate (the parent transform may be rotated and scaled), but it's useful. Available since: Open Surge 0.5.1","title":"lossyScale"},{"location":"engine/transform/#right","text":"right : Vector2 object, read-only. The right vector of the transform in world space. Unlike Vector2.right , this property considers the rotation of the transform. Available since: Open Surge 0.5.1","title":"right"},{"location":"engine/transform/#up","text":"up : Vector2 object, read-only. The up vector of the transform in world space. Unlike Vector2.up , this property considers the rotation of the transform. Available since: Open Surge 0.5.1","title":"up"},{"location":"engine/transform/#functions","text":"","title":"Functions"},{"location":"engine/transform/#translateby","text":"translateBy(dx, dy) Translates (moves) the object by ( dx , dy ). Available since: Open Surge 0.5.1. See the note below. Arguments dx : number. Specifies how much to move the object in the x-axis. dy : number. Specifies how much to move the object in the y-axis. Example using SurgeEngine.Actor ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // move the entity at a speed of // 50 pixels/second, to the right transform . translateBy ( 50 * Time . delta , 0 ); // the command below would move it // at a speed of 30 pixels per FRAME //transform.translateBy(30, 0); // don't do this // since the framerate may vary across // different systems, it's advisable // to multiply the value by Time.delta // to make the behavior consistent. } } Note: in versions prior to 0.5.1, this function was called move .","title":"translateBy"},{"location":"engine/transform/#translate","text":"translate(delta) Translates the object by a delta vector. Arguments delta : Vector2 object.","title":"translate"},{"location":"engine/transform/#rotate","text":"rotate(deg) Rotates the object by deg degrees. Arguments deg : number. An angle in degrees. Example using SurgeEngine.Actor ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { // rotate the entity at a speed of // 45 degrees per second transform . rotate ( 45 * Time . delta ); } }","title":"rotate"},{"location":"engine/transform/#scaleby","text":"scaleBy(sx, sy) Scales the object by horizontal and vertical factors sx and sy , respectively. Available since: Open Surge 0.6.1. Arguments sx : number. Horizontal scale factor. Value 1.0 means no change. sy : number. Vertical scale factor. Value 1.0 means no change.","title":"scaleBy"},{"location":"engine/transform/#scale","text":"scale(resize) Scales the object by a resize vector. Available since: Open Surge 0.6.1. Arguments resize : Vector2 object. Vector2(1,1) means no change.","title":"scale"},{"location":"engine/transform/#lookat","text":"lookAt(position) Rotates the transform so that its right vector points at the given position. Use this function to make your object look at some point in world space. Available since: Open Surge 0.5.1. See the note below. Arguments position : Vector2 object. A point in world space. Example using SurgeEngine.Actor ; using SurgeEngine.Player ; using SurgeEngine.Transform ; object \"My Level Object\" is \"entity\" { public transform = Transform (); actor = Actor ( \"My Level Object\" ); state \"main\" { player = Player . active ; transform . lookAt ( player . transform . position ); } } Note: in versions prior to 0.5.1, this function accepted a Transform parameter.","title":"lookAt"},{"location":"engine/vector2/","text":"Vector2 Vector2 is a vector in 2D space. A vector is a mathematical object that has direction and length, usually represented by an arrow. A Vector2 can also be represented by a pair of (x,y) coordinates. In SurgeScript, vectors are immutable. Once created, you can't change their coordinates directly. In order to bring about change (say, in the position of an entity ), you need to create a new vector. Vector2 objects have been designed in such a way that their functions make them chainable. You can compose different vector operations using english-based terms, as in the example below: Example using SurgeEngine.Player ; using SurgeEngine.Vector2 ; ... player = Player . active ; ... l = Vector2 ( 6 , 8 ). scaledBy ( 0.5 ). length ; // number five u = Vector2 . right . rotatedBy ( 45 ). scaledBy ( 2 ); // a vector v = player . transform . position . translatedBy ( 5 , 0 ); // a vector ... Note: In Open Surge, the x-axis grows to the right of the screen and the y-axis grows downwards, as in many other 2D games and software. Factory Vector2 Vector2(x, y) Spawns a 2D vector with the given coordinates. Arguments x : number. The x-coordinate of the vector. y : number. The y-coordinate of the vector. Returns A Vector2 object. Example using SurgeEngine.Vector2 ; using SurgeEngine.Player ; // This entity will lock the player on position (100, 100) object \"PlayerLocker\" is \"entity\" , \"awake\" { pos = Vector2 ( 100 , 100 ); state \"main\" { player = Player . active ; player . transform . position = pos ; } } Static properties Vector2.up Vector2.up The unit up vector, i.e., (0,-1). Vector2.right Vector2.right The unit right vector, i.e., (1,0). Vector2.down Vector2.down The unit down vector, i.e., (0,1). Vector2.left Vector2.left The unit left vector, i.e., (-1,0). Vector2.zero Vector2.zero The zero vector, i.e., (0,0). Vector2.one Vector2.one The (1,1) vector. Available since: Open Surge 0.6.1 Properties x x : number, read-only. The x-coordinate of the vector. y y : number, read-only. The y-coordinate of the vector. length length : number, read-only. The length of the vector. angle angle : number, read-only. The angle, in degrees, between the vector and the positive x-axis (as in polar coordinates). Functions plus plus(v) Returns a Vector2 corresponding to the addition between this and v . Arguments v : Vector2 object. Returns Returns a Vector2 object corresponding to the result of the operation. Example a = Vector2 ( 3 , 1 ); b = Vector2 ( 2 , 1 ); c = a . plus ( b ); // c = (5,2) minus minus(v) Returns a Vector2 corresponding to the subtraction between this and v . Arguments v : Vector2 object. Returns Returns a Vector2 object corresponding to the result of the operation. Example v = Vector2 ( 5 , 5 ); zero = v . minus ( v ); // zero = (0,0) dot dot(v) Returns the dot product between this and v . Arguments v : Vector2 object. Returns Returns a number: the dot product between this and v . normalized normalized() Returns a normalized copy of this : the new vector will have length one. Returns Returns a Vector2 object corresponding to the result of the operation. directionTo directionTo(v) Returns a unit vector pointing to v (from this ). Arguments v : Vector2 object. Returns Returns a Vector2 of length one corresponding to the result of the operation. distanceTo distanceTo(v) Considering this and v as points in space, this function returns the distance between them. Arguments v : Vector2 object. Returns Returns a number corresponding to the specified distance. Example using SurgeEngine.Transform ; using SurgeEngine.Player ; // This entity will show the distance between // itself and the active player object \"DistanceDebugger\" is \"entity\" , \"awake\" { transform = Transform (); state \"main\" { player = Player . active ; playerpos = player . transform . position ; distance = transform . position . distanceTo ( playerpos ); Console . print ( distance ); } } translatedBy translatedBy(dx,dy) Returns a copy of this translated by (dx,dy) . Arguments dx : number. The offset to be added to the x-coordinate. dy : number. The offset to be added to the y-coordinate. Returns Returns a Vector2 object corresponding to the result of the operation. Example using SurgeEngine.Vector2 ; ... v = Vector2 . one . translatedBy ( 4 , 5 ); // (5,6) rotatedBy rotatedBy(deg) Returns a copy of this rotated counterclockwise by deg degrees. Arguments deg : number. The amount of degrees used on the rotation. Returns Returns a Vector2 object corresponding to the result of the operation. Example using SurgeEngine.Vector2 ; ... // A unit vector with an angle of 45 degrees // (relative to the positive x-axis) v = Vector2 . right . rotatedBy ( 45 ); Note: in Open Surge, the y-axis grows downwards. As an example, Vector2.right (1,0) rotated counterclockwise by 90 degrees will be the same as Vector2.up (0,-1). In addition, to rotate a Vector2 by deg degrees clockwise you may rotate it by -deg degrees counterclockwise. scaledBy scaledBy(s) Returns a copy of this scaled by s . The length of the resulting vector will be the length of this multiplied by s . Arguments s : number. The multiplier. Returns Returns a Vector2 object corresponding to the result of the operation. Example using SurgeEngine.Vector2 ; ... one = Vector2 . one ; two = one . scaledBy ( 2 ); // (2,2) half = one . scaledBy ( 0.5 ); // (0.5,0.5) projectedOn projectedOn(v) Returns a copy of this projected on nonzero vector v . Arguments v : Vector2 object. Returns Returns a Vector2 object corresponding to the result of the operation. toString toString() Converts the vector to a string. Returns Returns a string containing the coordinates of this . Example using SurgeEngine.Vector2 ; ... Console . print ( Vector2 . one ); // using toString() implicitly","title":"Vector2"},{"location":"engine/vector2/#vector2","text":"Vector2 is a vector in 2D space. A vector is a mathematical object that has direction and length, usually represented by an arrow. A Vector2 can also be represented by a pair of (x,y) coordinates. In SurgeScript, vectors are immutable. Once created, you can't change their coordinates directly. In order to bring about change (say, in the position of an entity ), you need to create a new vector. Vector2 objects have been designed in such a way that their functions make them chainable. You can compose different vector operations using english-based terms, as in the example below: Example using SurgeEngine.Player ; using SurgeEngine.Vector2 ; ... player = Player . active ; ... l = Vector2 ( 6 , 8 ). scaledBy ( 0.5 ). length ; // number five u = Vector2 . right . rotatedBy ( 45 ). scaledBy ( 2 ); // a vector v = player . transform . position . translatedBy ( 5 , 0 ); // a vector ... Note: In Open Surge, the x-axis grows to the right of the screen and the y-axis grows downwards, as in many other 2D games and software.","title":"Vector2"},{"location":"engine/vector2/#factory","text":"","title":"Factory"},{"location":"engine/vector2/#vector2_1","text":"Vector2(x, y) Spawns a 2D vector with the given coordinates. Arguments x : number. The x-coordinate of the vector. y : number. The y-coordinate of the vector. Returns A Vector2 object. Example using SurgeEngine.Vector2 ; using SurgeEngine.Player ; // This entity will lock the player on position (100, 100) object \"PlayerLocker\" is \"entity\" , \"awake\" { pos = Vector2 ( 100 , 100 ); state \"main\" { player = Player . active ; player . transform . position = pos ; } }","title":"Vector2"},{"location":"engine/vector2/#static-properties","text":"","title":"Static properties"},{"location":"engine/vector2/#vector2up","text":"Vector2.up The unit up vector, i.e., (0,-1).","title":"Vector2.up"},{"location":"engine/vector2/#vector2right","text":"Vector2.right The unit right vector, i.e., (1,0).","title":"Vector2.right"},{"location":"engine/vector2/#vector2down","text":"Vector2.down The unit down vector, i.e., (0,1).","title":"Vector2.down"},{"location":"engine/vector2/#vector2left","text":"Vector2.left The unit left vector, i.e., (-1,0).","title":"Vector2.left"},{"location":"engine/vector2/#vector2zero","text":"Vector2.zero The zero vector, i.e., (0,0).","title":"Vector2.zero"},{"location":"engine/vector2/#vector2one","text":"Vector2.one The (1,1) vector. Available since: Open Surge 0.6.1","title":"Vector2.one"},{"location":"engine/vector2/#properties","text":"","title":"Properties"},{"location":"engine/vector2/#x","text":"x : number, read-only. The x-coordinate of the vector.","title":"x"},{"location":"engine/vector2/#y","text":"y : number, read-only. The y-coordinate of the vector.","title":"y"},{"location":"engine/vector2/#length","text":"length : number, read-only. The length of the vector.","title":"length"},{"location":"engine/vector2/#angle","text":"angle : number, read-only. The angle, in degrees, between the vector and the positive x-axis (as in polar coordinates).","title":"angle"},{"location":"engine/vector2/#functions","text":"","title":"Functions"},{"location":"engine/vector2/#plus","text":"plus(v) Returns a Vector2 corresponding to the addition between this and v . Arguments v : Vector2 object. Returns Returns a Vector2 object corresponding to the result of the operation. Example a = Vector2 ( 3 , 1 ); b = Vector2 ( 2 , 1 ); c = a . plus ( b ); // c = (5,2)","title":"plus"},{"location":"engine/vector2/#minus","text":"minus(v) Returns a Vector2 corresponding to the subtraction between this and v . Arguments v : Vector2 object. Returns Returns a Vector2 object corresponding to the result of the operation. Example v = Vector2 ( 5 , 5 ); zero = v . minus ( v ); // zero = (0,0)","title":"minus"},{"location":"engine/vector2/#dot","text":"dot(v) Returns the dot product between this and v . Arguments v : Vector2 object. Returns Returns a number: the dot product between this and v .","title":"dot"},{"location":"engine/vector2/#normalized","text":"normalized() Returns a normalized copy of this : the new vector will have length one. Returns Returns a Vector2 object corresponding to the result of the operation.","title":"normalized"},{"location":"engine/vector2/#directionto","text":"directionTo(v) Returns a unit vector pointing to v (from this ). Arguments v : Vector2 object. Returns Returns a Vector2 of length one corresponding to the result of the operation.","title":"directionTo"},{"location":"engine/vector2/#distanceto","text":"distanceTo(v) Considering this and v as points in space, this function returns the distance between them. Arguments v : Vector2 object. Returns Returns a number corresponding to the specified distance. Example using SurgeEngine.Transform ; using SurgeEngine.Player ; // This entity will show the distance between // itself and the active player object \"DistanceDebugger\" is \"entity\" , \"awake\" { transform = Transform (); state \"main\" { player = Player . active ; playerpos = player . transform . position ; distance = transform . position . distanceTo ( playerpos ); Console . print ( distance ); } }","title":"distanceTo"},{"location":"engine/vector2/#translatedby","text":"translatedBy(dx,dy) Returns a copy of this translated by (dx,dy) . Arguments dx : number. The offset to be added to the x-coordinate. dy : number. The offset to be added to the y-coordinate. Returns Returns a Vector2 object corresponding to the result of the operation. Example using SurgeEngine.Vector2 ; ... v = Vector2 . one . translatedBy ( 4 , 5 ); // (5,6)","title":"translatedBy"},{"location":"engine/vector2/#rotatedby","text":"rotatedBy(deg) Returns a copy of this rotated counterclockwise by deg degrees. Arguments deg : number. The amount of degrees used on the rotation. Returns Returns a Vector2 object corresponding to the result of the operation. Example using SurgeEngine.Vector2 ; ... // A unit vector with an angle of 45 degrees // (relative to the positive x-axis) v = Vector2 . right . rotatedBy ( 45 ); Note: in Open Surge, the y-axis grows downwards. As an example, Vector2.right (1,0) rotated counterclockwise by 90 degrees will be the same as Vector2.up (0,-1). In addition, to rotate a Vector2 by deg degrees clockwise you may rotate it by -deg degrees counterclockwise.","title":"rotatedBy"},{"location":"engine/vector2/#scaledby","text":"scaledBy(s) Returns a copy of this scaled by s . The length of the resulting vector will be the length of this multiplied by s . Arguments s : number. The multiplier. Returns Returns a Vector2 object corresponding to the result of the operation. Example using SurgeEngine.Vector2 ; ... one = Vector2 . one ; two = one . scaledBy ( 2 ); // (2,2) half = one . scaledBy ( 0.5 ); // (0.5,0.5)","title":"scaledBy"},{"location":"engine/vector2/#projectedon","text":"projectedOn(v) Returns a copy of this projected on nonzero vector v . Arguments v : Vector2 object. Returns Returns a Vector2 object corresponding to the result of the operation.","title":"projectedOn"},{"location":"engine/vector2/#tostring","text":"toString() Converts the vector to a string. Returns Returns a string containing the coordinates of this . Example using SurgeEngine.Vector2 ; ... Console . print ( Vector2 . one ); // using toString() implicitly","title":"toString"},{"location":"engine/video/","text":"Video Video settings. Example // display the current Video mode using SurgeEngine.Video ; object \"Application\" { state \"main\" { Console . print ( Video . mode ); state = \"done\" ; } state \"done\" { } } Properties fullscreen fullscreen : boolean. Whether or not the engine is running on fullscreen mode. Use this property to toggle between windowed and fullscreen modes. Available since: Open Surge 0.6.1 mode mode : string. The current video mode. The following are the valid values: \"default\" : the size of the screen is set to its default. \"fill\" : the size of the screen is set to the size of the window. \"best-fit\" : similar to \"fill\" , except that the aspect ratio of the default size of the screen is maintained. Available since: Open Surge 0.6.1","title":"Video"},{"location":"engine/video/#video","text":"Video settings. Example // display the current Video mode using SurgeEngine.Video ; object \"Application\" { state \"main\" { Console . print ( Video . mode ); state = \"done\" ; } state \"done\" { } }","title":"Video"},{"location":"engine/video/#properties","text":"","title":"Properties"},{"location":"engine/video/#fullscreen","text":"fullscreen : boolean. Whether or not the engine is running on fullscreen mode. Use this property to toggle between windowed and fullscreen modes. Available since: Open Surge 0.6.1","title":"fullscreen"},{"location":"engine/video/#mode","text":"mode : string. The current video mode. The following are the valid values: \"default\" : the size of the screen is set to its default. \"fill\" : the size of the screen is set to the size of the window. \"best-fit\" : similar to \"fill\" , except that the aspect ratio of the default size of the screen is maintained. Available since: Open Surge 0.6.1","title":"mode"},{"location":"engine/web/","text":"Web Web routines. Functions launchURL launchURL(url) Launches a URL using the default web browser. It's mandatory to specify a protocol. The following protocols are currently supported: http:// , https:// , mailto: Arguments url : string. The URL to be launched. Example using SurgeEngine.Web ; object \"Application\" { // Remember to change the state // after calling launchURL state \"main\" { Web . launchURL ( \"http://opensurge2d.org\" ); state = \"done\" ; } state \"done\" { } } encodeURIComponent encodeURIComponent(str) Encodes a component of a Universal Resource Identifier (URI). It escapes all characters of the input string, except: A\u2013Z a\u2013z 0\u20139 - _ . ! ~ * ' ( ) Arguments str : string. The string to be escaped. Returns Returns the input string escaped as above. Example using SurgeEngine.Web ; // ... user = \"Jane Doe\" ; url = \"https://my.website.name/?user=\" + Web . encodeURIComponent ( user ); Console . print ( url ); // output: // https://my.website.name/?user=Jane%20Doe Available since: Open Surge 0.6.1","title":"Web"},{"location":"engine/web/#web","text":"Web routines.","title":"Web"},{"location":"engine/web/#functions","text":"","title":"Functions"},{"location":"engine/web/#launchurl","text":"launchURL(url) Launches a URL using the default web browser. It's mandatory to specify a protocol. The following protocols are currently supported: http:// , https:// , mailto: Arguments url : string. The URL to be launched. Example using SurgeEngine.Web ; object \"Application\" { // Remember to change the state // after calling launchURL state \"main\" { Web . launchURL ( \"http://opensurge2d.org\" ); state = \"done\" ; } state \"done\" { } }","title":"launchURL"},{"location":"engine/web/#encodeuricomponent","text":"encodeURIComponent(str) Encodes a component of a Universal Resource Identifier (URI). It escapes all characters of the input string, except: A\u2013Z a\u2013z 0\u20139 - _ . ! ~ * ' ( ) Arguments str : string. The string to be escaped. Returns Returns the input string escaped as above. Example using SurgeEngine.Web ; // ... user = \"Jane Doe\" ; url = \"https://my.website.name/?user=\" + Web . encodeURIComponent ( user ); Console . print ( url ); // output: // https://my.website.name/?user=Jane%20Doe Available since: Open Surge 0.6.1","title":"encodeURIComponent"},{"location":"reference/application/","text":"Application Represents the Application. You do not need to instantiate it, as it is instantiated automatically. This object can be accessed by any other object, in any script, simply by typing Application . Properties args args : Arguments object, read-only. Use this property to read the command line arguments. Functions exit exit() Exits the Application. crash crash(message) Exits the Application with an error message. Arguments message : string. The message to be displayed to the user. destroy destroy() A synonym for Application.exit() .","title":"Application"},{"location":"reference/application/#application","text":"Represents the Application. You do not need to instantiate it, as it is instantiated automatically. This object can be accessed by any other object, in any script, simply by typing Application .","title":"Application"},{"location":"reference/application/#properties","text":"","title":"Properties"},{"location":"reference/application/#args","text":"args : Arguments object, read-only. Use this property to read the command line arguments.","title":"args"},{"location":"reference/application/#functions","text":"","title":"Functions"},{"location":"reference/application/#exit","text":"exit() Exits the Application.","title":"exit"},{"location":"reference/application/#crash","text":"crash(message) Exits the Application with an error message. Arguments message : string. The message to be displayed to the user.","title":"crash"},{"location":"reference/application/#destroy","text":"destroy() A synonym for Application.exit() .","title":"destroy"},{"location":"reference/arguments/","text":"Arguments If you've launched your application via the command-line, this Array-like object can be used to read command-line arguments. This is available at Application.args . The example below prints all the arguments to the screen: // Method 1 (foreach) foreach ( argument in Application . args ) Console . print ( argument ); // Method 2 (for loops) for ( i = 0 ; i < Application . args . length ; i ++) Console . print ( Application . args [ i ]); // Or, alternatively: Console . print ( Application . args ); Properties length length : number, read-only. The number of command-line arguments, including the executable. Functions get get(index) Gets the specified command-line argument. Instead of calling get() , one may use equivalently the [ ] operator. Arguments index : integer number between 0 and Application.args.length - 1 , inclusive. Returns A string with the specified command-line argument, or null if there is no such argument. Example // Suppose that you run surgescript via the command-line: // surgescript test_args.ss executable = Application . args [ 0 ]; // \"surgescript\" script_file = Application . args [ 1 ]; // \"test_args.ss\" option option(optionName) Gets the value of a certain command-line option. Arguments optionName : string. The option you want to read. Returns A string featuring the value of the desired command-line option, or null if such an option hasn't been provided by the user. Example // Suppose that you run surgescript via the command-line: // surgescript test_args.ss --my-option 12345 my_option = Application . args . option ( \"--my-option\" ); // Options -p and --port are equivalent // surgescript test_args.ss -p 80 // surgescript test_args.ss --port 80 port = Application . args . option ( \"--port\" ) || Application . args . option ( \"-p\" ); // Default values (useful if the option is not present) // surgescript test_args.ss // surgescript test_args.ss --name alice name = Application . args . option ( \"--name\" ) || \"anonymous\" ; hasOption hasOption(optionName) Checks if the specified option is present in the command-line. Arguments optionName : string. Returns Returns true if the specified option is present in the command-line; or false otherwise. iterator iterator() Spawns an iterator. Returns An iterator to iterate over the command-line arguments. toString toString() Converts the command-line arguments to a string. Returns A string featuring the command-line arguments.","title":"Arguments"},{"location":"reference/arguments/#arguments","text":"If you've launched your application via the command-line, this Array-like object can be used to read command-line arguments. This is available at Application.args . The example below prints all the arguments to the screen: // Method 1 (foreach) foreach ( argument in Application . args ) Console . print ( argument ); // Method 2 (for loops) for ( i = 0 ; i < Application . args . length ; i ++) Console . print ( Application . args [ i ]); // Or, alternatively: Console . print ( Application . args );","title":"Arguments"},{"location":"reference/arguments/#properties","text":"","title":"Properties"},{"location":"reference/arguments/#length","text":"length : number, read-only. The number of command-line arguments, including the executable.","title":"length"},{"location":"reference/arguments/#functions","text":"","title":"Functions"},{"location":"reference/arguments/#get","text":"get(index) Gets the specified command-line argument. Instead of calling get() , one may use equivalently the [ ] operator. Arguments index : integer number between 0 and Application.args.length - 1 , inclusive. Returns A string with the specified command-line argument, or null if there is no such argument. Example // Suppose that you run surgescript via the command-line: // surgescript test_args.ss executable = Application . args [ 0 ]; // \"surgescript\" script_file = Application . args [ 1 ]; // \"test_args.ss\"","title":"get"},{"location":"reference/arguments/#option","text":"option(optionName) Gets the value of a certain command-line option. Arguments optionName : string. The option you want to read. Returns A string featuring the value of the desired command-line option, or null if such an option hasn't been provided by the user. Example // Suppose that you run surgescript via the command-line: // surgescript test_args.ss --my-option 12345 my_option = Application . args . option ( \"--my-option\" ); // Options -p and --port are equivalent // surgescript test_args.ss -p 80 // surgescript test_args.ss --port 80 port = Application . args . option ( \"--port\" ) || Application . args . option ( \"-p\" ); // Default values (useful if the option is not present) // surgescript test_args.ss // surgescript test_args.ss --name alice name = Application . args . option ( \"--name\" ) || \"anonymous\" ;","title":"option"},{"location":"reference/arguments/#hasoption","text":"hasOption(optionName) Checks if the specified option is present in the command-line. Arguments optionName : string. Returns Returns true if the specified option is present in the command-line; or false otherwise.","title":"hasOption"},{"location":"reference/arguments/#iterator","text":"iterator() Spawns an iterator. Returns An iterator to iterate over the command-line arguments.","title":"iterator"},{"location":"reference/arguments/#tostring","text":"toString() Converts the command-line arguments to a string. Returns A string featuring the command-line arguments.","title":"toString"},{"location":"reference/array/","text":"Array An Array is a collection of values organized in sequencial fashion. To instantiate an Array, use the [ value_1, value_2, ..., value_n ] syntax rather than the spawn() function. Example: object \"Application\" { // The 'characters' array hold 3 strings characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; state \"main\" { // who are the characters? Console . print ( \"The characters are:\" ); Console . print ( characters [ 0 ]); Console . print ( characters [ 1 ]); Console . print ( characters [ 2 ]); // how many characters? Console . print ( \"Number of characters: \" + characters . length ); } } Output: The characters are: Surge Neon Charge Number of characters: 3 Caution! Whenever you define an array, you spawn a new object. You are advised to NOT define arrays within states, because the code within the states run continuously. New objects will be created at every frame, not just once. In the above example, the characters array is defined as an object-level variable . Properties length length : number, read-only. The number of elements in the Array. Functions get get(index) Gets the specified element of the Array. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments index : integer number between 0 and this.length - 1 , inclusive. Returns The Array element at position index (0-based). Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; ... surge = characters [ 0 ]; // first element (\"Surge\") neon = characters [ 1 ]; // second element (\"Neon\") charge = characters [ 2 ]; // third element (\"Charge\") set set(index, value) Sets to value the element of the Array at position index . Instead of calling set() directly, you may equivalently use the [ ] operator. Arguments index : integer number between 0 and this.length - 1 , inclusive. value : any type. The new value to be placed on the Array. Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; characters [ 0 ] = \"Gimacian\" ; Console . print ( characters [ 0 ]); // Gimacian push push(value) Adds a new element to the end of the Array. Arguments value : any type. The element to be added to the Array. Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; characters . push ( \"Gimacian\" ); Console . print ( characters ); // [ \"Surge\", \"Neon\", \"Charge\", \"Gimacian\" ] pop pop() Removes the last element of the Array and returns it. Returns The removed element. shift shift() Removes the first element of the Array and returns it. Returns The removed element. unshift unshift(value) Adds a new element to the beginning of the Array. Arguments value : any type. The element to be added to the Array. clear clear() Clears the array. It will no longer hold any elements and its length will be set to zero. Available since: SurgeScript 0.5.3 indexOf indexOf(value) Search the Array for element value and return its position. Arguments value : any type. The element to be searched for. Returns The position of the searched element - a number between 0 and this.length - 1 , inclusive. If the desired element is not found, this function returns -1 . Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; ... two = characters . indexOf ( \"Neon\" ); // 2 gimacian = characters . indexOf ( \"Gimacian\" ); // -1 if ( gimacian < 0 ) Console . print ( \"Not found\" ); sort sort(cmpFun) Sorts the Array. If no comparison functor is provided ( cmpFun is null ), the Array will be sorted in ascending order. Arguments cmpFun : object | null. This functor implements function call(a, b) that compares two array elements as described in the example below. Returns The sorted array. The returned array is the same array as you called sort() on; it's not a copy. Example // this example will print the elements // of the Array in ascending order object \"Application\" { arr = [ 3 , 9 , 4 , 8 , 5 , 6 , 7 , 1 , 2 , 0 ]; state \"main\" { // sort and print the Array arr . sort ( null ); Console . print ( arr ); Application . exit (); } } Output: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] // this example will print the elements // of the Array in descending order object \"Application\" { arr = [ 3 , 9 , 4 , 8 , 5 , 6 , 7 , 1 , 2 , 0 ]; cmp = spawn ( \"Sort.OrderByDesc\" ); state \"main\" { // sort and print the Array arr . sort ( cmp ); Console . print ( arr ); Application . exit (); } } object \"Sort.OrderByDesc\" { // This function compares two // elements of the Array: a and b. // // It should return a number: // < 0 if a must come BEFORE b // = 0 if a and b are equivalent // > 0 if a must come AFTER b fun call ( a , b ) { // sort in descending order return b - a ; } } Output: [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ] reverse reverse() Reverses the order of the elements in the Array. shuffle shuffle() Shuffles the elements of the Array, placing its elements at random spots. iterator iterator() Spawns an iterator. Returns An iterator to loop through the elements of the Array. toString toString() Converts the Array to a string. Returns A string.","title":"Array"},{"location":"reference/array/#array","text":"An Array is a collection of values organized in sequencial fashion. To instantiate an Array, use the [ value_1, value_2, ..., value_n ] syntax rather than the spawn() function. Example: object \"Application\" { // The 'characters' array hold 3 strings characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; state \"main\" { // who are the characters? Console . print ( \"The characters are:\" ); Console . print ( characters [ 0 ]); Console . print ( characters [ 1 ]); Console . print ( characters [ 2 ]); // how many characters? Console . print ( \"Number of characters: \" + characters . length ); } } Output: The characters are: Surge Neon Charge Number of characters: 3 Caution! Whenever you define an array, you spawn a new object. You are advised to NOT define arrays within states, because the code within the states run continuously. New objects will be created at every frame, not just once. In the above example, the characters array is defined as an object-level variable .","title":"Array"},{"location":"reference/array/#properties","text":"","title":"Properties"},{"location":"reference/array/#length","text":"length : number, read-only. The number of elements in the Array.","title":"length"},{"location":"reference/array/#functions","text":"","title":"Functions"},{"location":"reference/array/#get","text":"get(index) Gets the specified element of the Array. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments index : integer number between 0 and this.length - 1 , inclusive. Returns The Array element at position index (0-based). Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; ... surge = characters [ 0 ]; // first element (\"Surge\") neon = characters [ 1 ]; // second element (\"Neon\") charge = characters [ 2 ]; // third element (\"Charge\")","title":"get"},{"location":"reference/array/#set","text":"set(index, value) Sets to value the element of the Array at position index . Instead of calling set() directly, you may equivalently use the [ ] operator. Arguments index : integer number between 0 and this.length - 1 , inclusive. value : any type. The new value to be placed on the Array. Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; characters [ 0 ] = \"Gimacian\" ; Console . print ( characters [ 0 ]); // Gimacian","title":"set"},{"location":"reference/array/#push","text":"push(value) Adds a new element to the end of the Array. Arguments value : any type. The element to be added to the Array. Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; characters . push ( \"Gimacian\" ); Console . print ( characters ); // [ \"Surge\", \"Neon\", \"Charge\", \"Gimacian\" ]","title":"push"},{"location":"reference/array/#pop","text":"pop() Removes the last element of the Array and returns it. Returns The removed element.","title":"pop"},{"location":"reference/array/#shift","text":"shift() Removes the first element of the Array and returns it. Returns The removed element.","title":"shift"},{"location":"reference/array/#unshift","text":"unshift(value) Adds a new element to the beginning of the Array. Arguments value : any type. The element to be added to the Array.","title":"unshift"},{"location":"reference/array/#clear","text":"clear() Clears the array. It will no longer hold any elements and its length will be set to zero. Available since: SurgeScript 0.5.3","title":"clear"},{"location":"reference/array/#indexof","text":"indexOf(value) Search the Array for element value and return its position. Arguments value : any type. The element to be searched for. Returns The position of the searched element - a number between 0 and this.length - 1 , inclusive. If the desired element is not found, this function returns -1 . Example characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; ... two = characters . indexOf ( \"Neon\" ); // 2 gimacian = characters . indexOf ( \"Gimacian\" ); // -1 if ( gimacian < 0 ) Console . print ( \"Not found\" );","title":"indexOf"},{"location":"reference/array/#sort","text":"sort(cmpFun) Sorts the Array. If no comparison functor is provided ( cmpFun is null ), the Array will be sorted in ascending order. Arguments cmpFun : object | null. This functor implements function call(a, b) that compares two array elements as described in the example below. Returns The sorted array. The returned array is the same array as you called sort() on; it's not a copy. Example // this example will print the elements // of the Array in ascending order object \"Application\" { arr = [ 3 , 9 , 4 , 8 , 5 , 6 , 7 , 1 , 2 , 0 ]; state \"main\" { // sort and print the Array arr . sort ( null ); Console . print ( arr ); Application . exit (); } } Output: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] // this example will print the elements // of the Array in descending order object \"Application\" { arr = [ 3 , 9 , 4 , 8 , 5 , 6 , 7 , 1 , 2 , 0 ]; cmp = spawn ( \"Sort.OrderByDesc\" ); state \"main\" { // sort and print the Array arr . sort ( cmp ); Console . print ( arr ); Application . exit (); } } object \"Sort.OrderByDesc\" { // This function compares two // elements of the Array: a and b. // // It should return a number: // < 0 if a must come BEFORE b // = 0 if a and b are equivalent // > 0 if a must come AFTER b fun call ( a , b ) { // sort in descending order return b - a ; } } Output: [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ]","title":"sort"},{"location":"reference/array/#reverse","text":"reverse() Reverses the order of the elements in the Array.","title":"reverse"},{"location":"reference/array/#shuffle","text":"shuffle() Shuffles the elements of the Array, placing its elements at random spots.","title":"shuffle"},{"location":"reference/array/#iterator","text":"iterator() Spawns an iterator. Returns An iterator to loop through the elements of the Array.","title":"iterator"},{"location":"reference/array/#tostring","text":"toString() Converts the Array to a string. Returns A string.","title":"toString"},{"location":"reference/boolean/","text":"Boolean Routines for booleans. The Boolean object is not supposed to be used directly. The functions below are available for primitive values of the boolean type. Functions valueOf valueOf() The primitive value of the boolean, i.e., the boolean itself. Returns The boolean. toString toString() Convert boolean to string. Returns The boolean converted to a string. equals equals(b) Compares the boolean to another boolean b . Arguments b : boolean. The value to compare the boolean to. Returns Returns true if the booleans are equal.","title":"Boolean"},{"location":"reference/boolean/#boolean","text":"Routines for booleans. The Boolean object is not supposed to be used directly. The functions below are available for primitive values of the boolean type.","title":"Boolean"},{"location":"reference/boolean/#functions","text":"","title":"Functions"},{"location":"reference/boolean/#valueof","text":"valueOf() The primitive value of the boolean, i.e., the boolean itself. Returns The boolean.","title":"valueOf"},{"location":"reference/boolean/#tostring","text":"toString() Convert boolean to string. Returns The boolean converted to a string.","title":"toString"},{"location":"reference/boolean/#equals","text":"equals(b) Compares the boolean to another boolean b . Arguments b : boolean. The value to compare the boolean to. Returns Returns true if the booleans are equal.","title":"equals"},{"location":"reference/console/","text":"Console The Console is a mechanism that allows users to interact with your app via a text-based interface. You can print data to the user and read data from the user. Functions print print(line) Prints a line to the console. Arguments line : string. The message to be printed. Example // this will print \"Hello, there!\" and quit object \"Application\" { state \"main\" { Console . print ( \"Hello, there!\" ); Application . exit (); } } write write(str) Writes a string to the console, without a line break at the end. Arguments str : string. The string to be written. readline readline() Reads a line from the standard input. Returns Returns the string just read, without a line break at the end. Example // will ask the name of the user until a name is given object \"Application\" { state \"main\" { Console . print ( \"Hey pal, what's your name? \" ); name = Console . readline (); if ( name != \"\" ) { Console . print ( \"Nice to meet you, \" + name ); Application . exit (); } } }","title":"Console"},{"location":"reference/console/#console","text":"The Console is a mechanism that allows users to interact with your app via a text-based interface. You can print data to the user and read data from the user.","title":"Console"},{"location":"reference/console/#functions","text":"","title":"Functions"},{"location":"reference/console/#print","text":"print(line) Prints a line to the console. Arguments line : string. The message to be printed. Example // this will print \"Hello, there!\" and quit object \"Application\" { state \"main\" { Console . print ( \"Hello, there!\" ); Application . exit (); } }","title":"print"},{"location":"reference/console/#write","text":"write(str) Writes a string to the console, without a line break at the end. Arguments str : string. The string to be written.","title":"write"},{"location":"reference/console/#readline","text":"readline() Reads a line from the standard input. Returns Returns the string just read, without a line break at the end. Example // will ask the name of the user until a name is given object \"Application\" { state \"main\" { Console . print ( \"Hey pal, what's your name? \" ); name = Console . readline (); if ( name != \"\" ) { Console . print ( \"Nice to meet you, \" + name ); Application . exit (); } } }","title":"readline"},{"location":"reference/date/","text":"Date Date is used to retrieve current date and time. You can access this object simply by typing Date . Example: // What day is today? object \"Application\" { // show the day state \"main\" { today = Date . year + \"-\" + f ( Date . month ) + \"-\" + f ( Date . day ); Console . print ( \"Today is \" + today ); Application . exit (); } // add a leading zero fun f ( x ) { if ( x >= 10 ) return x ; else return \"0\" + x ; } } Available since: SurgeScript 0.5.2 Properties year year : number, read-only. The current year. month month : number, read-only. Month of the year (1-12). day day : number. Day of the month (1-31). hour hour : number. Hours since midnight (0-23). minute minute : number. Minutes after the hour (0-59). second second : number. Seconds after the minute (0-59). weekday weekday : number. Days since Sunday (0-6). unixtime unixtime : number. Number of seconds since Jan 1st, 1970 00:00:00 UTC. Functions timezoneOffset timezoneOffset() The difference, in minutes, from the Coordinated Universal Time (UTC) to the timezone of the host. Example: if your timezone is UTC-03:00, this function returns -180. Available since: SurgeScript 0.5.2 Returns The timezone difference in minutes. toString toString() Converts the current date and time to a string. The string is formatted according to the ISO 8601 standard. Available since: SurgeScript 0.5.2 Returns The current date and time expressed according to ISO 8601.","title":"Date"},{"location":"reference/date/#date","text":"Date is used to retrieve current date and time. You can access this object simply by typing Date . Example: // What day is today? object \"Application\" { // show the day state \"main\" { today = Date . year + \"-\" + f ( Date . month ) + \"-\" + f ( Date . day ); Console . print ( \"Today is \" + today ); Application . exit (); } // add a leading zero fun f ( x ) { if ( x >= 10 ) return x ; else return \"0\" + x ; } } Available since: SurgeScript 0.5.2","title":"Date"},{"location":"reference/date/#properties","text":"","title":"Properties"},{"location":"reference/date/#year","text":"year : number, read-only. The current year.","title":"year"},{"location":"reference/date/#month","text":"month : number, read-only. Month of the year (1-12).","title":"month"},{"location":"reference/date/#day","text":"day : number. Day of the month (1-31).","title":"day"},{"location":"reference/date/#hour","text":"hour : number. Hours since midnight (0-23).","title":"hour"},{"location":"reference/date/#minute","text":"minute : number. Minutes after the hour (0-59).","title":"minute"},{"location":"reference/date/#second","text":"second : number. Seconds after the minute (0-59).","title":"second"},{"location":"reference/date/#weekday","text":"weekday : number. Days since Sunday (0-6).","title":"weekday"},{"location":"reference/date/#unixtime","text":"unixtime : number. Number of seconds since Jan 1st, 1970 00:00:00 UTC.","title":"unixtime"},{"location":"reference/date/#functions","text":"","title":"Functions"},{"location":"reference/date/#timezoneoffset","text":"timezoneOffset() The difference, in minutes, from the Coordinated Universal Time (UTC) to the timezone of the host. Example: if your timezone is UTC-03:00, this function returns -180. Available since: SurgeScript 0.5.2 Returns The timezone difference in minutes.","title":"timezoneOffset"},{"location":"reference/date/#tostring","text":"toString() Converts the current date and time to a string. The string is formatted according to the ISO 8601 standard. Available since: SurgeScript 0.5.2 Returns The current date and time expressed according to ISO 8601.","title":"toString"},{"location":"reference/dictionary/","text":"Dictionary A Dictionary is a collection of key-value pairs. Dictionary keys are strings. Their corresponding values can be of any type. To create a Dictionary, use the { key_1: value_1, key_2: value_2, ..., key_n: value_n } syntax rather than the spawn() function. Example: object \"Application\" { dictionary = { \"Surge\" : 35 , \"Neon\" : 20 , \"Charge\" : 37.5 , \"Gimacian\" : 70 }; state \"main\" { // usage example Console . print ( dictionary [ \"Surge\" ]); // will print 35 Console . print ( dictionary [ \"Neon\" ]); // will print 20 // will print all entries foreach ( entry in dictionary ) Console . print ( entry . key + \": \" + entry . value ); // done! Application . exit (); } } Output: 35 20 Surge: 35 Neon: 20 Charge: 37.5 Gimacian: 70 Caution! Whenever you define a dictionary, you spawn a new object. You are advised to NOT define dictionaries within states, because the code within the states run continuously. New objects will be created at every frame, not just once. In the above example, dictionary is defined as an object-level variable . Properties count count : number, read-only. The number of elements in the Dictionary. Functions get get(key) Gets the value of the specified key in the Dictionary. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments key : string. Returns The value corresponding to the specified key, or null if there is no such an entry in the Dictionary. Example dict = { \"Surge\" : 10 }; ten = dict [ \"Surge\" ]; set set(key, value) Sets the value of the specified key in the Dictionary. Instead of calling set() directly, you may equivalently use the [ ] operator. Arguments key : string. value : any type. Example dict = { }; dict [ \"Surge\" ] = 10 ; clear clear() Removes all entries from the Dictionary. delete delete(key) Deletes the entry having the specified key. Arguments key : string. The key of the entry to be removed. has has(key) Checks if an entry having the specified key belongs to the Dictionary. Arguments key : string. The key of the entry. Returns Returns true if the Dictionary has such an entry. keys keys() Gets a collection containing the keys of the Dictionary. Returns Returns a new Array containing the keys of the Dictionary. iterator iterator() Spawns an iterator. Returns An iterator to loop through the elements of the Dictionary. toString toString() Converts the Dictionary to a string. Returns A string.","title":"Dictionary"},{"location":"reference/dictionary/#dictionary","text":"A Dictionary is a collection of key-value pairs. Dictionary keys are strings. Their corresponding values can be of any type. To create a Dictionary, use the { key_1: value_1, key_2: value_2, ..., key_n: value_n } syntax rather than the spawn() function. Example: object \"Application\" { dictionary = { \"Surge\" : 35 , \"Neon\" : 20 , \"Charge\" : 37.5 , \"Gimacian\" : 70 }; state \"main\" { // usage example Console . print ( dictionary [ \"Surge\" ]); // will print 35 Console . print ( dictionary [ \"Neon\" ]); // will print 20 // will print all entries foreach ( entry in dictionary ) Console . print ( entry . key + \": \" + entry . value ); // done! Application . exit (); } } Output: 35 20 Surge: 35 Neon: 20 Charge: 37.5 Gimacian: 70 Caution! Whenever you define a dictionary, you spawn a new object. You are advised to NOT define dictionaries within states, because the code within the states run continuously. New objects will be created at every frame, not just once. In the above example, dictionary is defined as an object-level variable .","title":"Dictionary"},{"location":"reference/dictionary/#properties","text":"","title":"Properties"},{"location":"reference/dictionary/#count","text":"count : number, read-only. The number of elements in the Dictionary.","title":"count"},{"location":"reference/dictionary/#functions","text":"","title":"Functions"},{"location":"reference/dictionary/#get","text":"get(key) Gets the value of the specified key in the Dictionary. Instead of calling get() directly, you may equivalently use the [ ] operator. Arguments key : string. Returns The value corresponding to the specified key, or null if there is no such an entry in the Dictionary. Example dict = { \"Surge\" : 10 }; ten = dict [ \"Surge\" ];","title":"get"},{"location":"reference/dictionary/#set","text":"set(key, value) Sets the value of the specified key in the Dictionary. Instead of calling set() directly, you may equivalently use the [ ] operator. Arguments key : string. value : any type. Example dict = { }; dict [ \"Surge\" ] = 10 ;","title":"set"},{"location":"reference/dictionary/#clear","text":"clear() Removes all entries from the Dictionary.","title":"clear"},{"location":"reference/dictionary/#delete","text":"delete(key) Deletes the entry having the specified key. Arguments key : string. The key of the entry to be removed.","title":"delete"},{"location":"reference/dictionary/#has","text":"has(key) Checks if an entry having the specified key belongs to the Dictionary. Arguments key : string. The key of the entry. Returns Returns true if the Dictionary has such an entry.","title":"has"},{"location":"reference/dictionary/#keys","text":"keys() Gets a collection containing the keys of the Dictionary. Returns Returns a new Array containing the keys of the Dictionary.","title":"keys"},{"location":"reference/dictionary/#iterator","text":"iterator() Spawns an iterator. Returns An iterator to loop through the elements of the Dictionary.","title":"iterator"},{"location":"reference/dictionary/#tostring","text":"toString() Converts the Dictionary to a string. Returns A string.","title":"toString"},{"location":"reference/gc/","text":"GC SurgeScript features a Garbage Collector (GC) that automatically disposes objects that cannot be reached from the root (i.e., their references are lost). The Garbage Collector is available at System.gc . Generally, you do not need to modify any of its settings. Properties interval interval : number, read-only. Every interval seconds, the garbage collector will be called automatically. Note: this property is read-only since SurgeScript 0.6.0. objectCount objectCount : number, read-only. How many objects were disposed when the garbage collector was last called. Functions collect collect() Calls the Garbage Collector manually. You generally don't need to call this.","title":"GC"},{"location":"reference/gc/#gc","text":"SurgeScript features a Garbage Collector (GC) that automatically disposes objects that cannot be reached from the root (i.e., their references are lost). The Garbage Collector is available at System.gc . Generally, you do not need to modify any of its settings.","title":"GC"},{"location":"reference/gc/#properties","text":"","title":"Properties"},{"location":"reference/gc/#interval","text":"interval : number, read-only. Every interval seconds, the garbage collector will be called automatically. Note: this property is read-only since SurgeScript 0.6.0.","title":"interval"},{"location":"reference/gc/#objectcount","text":"objectCount : number, read-only. How many objects were disposed when the garbage collector was last called.","title":"objectCount"},{"location":"reference/gc/#functions","text":"","title":"Functions"},{"location":"reference/gc/#collect","text":"collect() Calls the Garbage Collector manually. You generally don't need to call this.","title":"collect"},{"location":"reference/iterator/","text":"Iterator In SurgeScript, Iterator is an abstract contract, or protocol, that define a set of functions that should be written in concrete implementations. If you're familiar with object oriented programming, Iterator is an interface. Iterators are used to traverse containers / collections / data structures and access its elements. Concrete implementations of Iterator include: ArrayIterator and DictionaryIterator . If you wish to write your own iterators , you need to specify the functions described below . The data structure that you wish to traverse should include an iterator() function that spawns the concrete implementation of the Iterator. Thus, the parent object of the Iterator will be the structure to be traversed. The basic usage of an Iterator is as follows: // container is an object such as an Array iterator = container . iterator (); // spawn an iterator to traverse the container while ( iterator . hasNext ()) { element = iterator . next (); Console . print ( element ); } Functions hasNext hasNext() Checks if there are more elements to be accessed in the iteration. Returns Returns true if there are more elements to be visited, or false otherwise. next next() Gets the next element of the container and advances the iteration. Returns The next element of the container, or null if there is no such element. The first call to next() returns the first element of the container, and so on.","title":"Iterator"},{"location":"reference/iterator/#iterator","text":"In SurgeScript, Iterator is an abstract contract, or protocol, that define a set of functions that should be written in concrete implementations. If you're familiar with object oriented programming, Iterator is an interface. Iterators are used to traverse containers / collections / data structures and access its elements. Concrete implementations of Iterator include: ArrayIterator and DictionaryIterator . If you wish to write your own iterators , you need to specify the functions described below . The data structure that you wish to traverse should include an iterator() function that spawns the concrete implementation of the Iterator. Thus, the parent object of the Iterator will be the structure to be traversed. The basic usage of an Iterator is as follows: // container is an object such as an Array iterator = container . iterator (); // spawn an iterator to traverse the container while ( iterator . hasNext ()) { element = iterator . next (); Console . print ( element ); }","title":"Iterator"},{"location":"reference/iterator/#functions","text":"","title":"Functions"},{"location":"reference/iterator/#hasnext","text":"hasNext() Checks if there are more elements to be accessed in the iteration. Returns Returns true if there are more elements to be visited, or false otherwise.","title":"hasNext"},{"location":"reference/iterator/#next","text":"next() Gets the next element of the container and advances the iteration. Returns The next element of the container, or null if there is no such element. The first call to next() returns the first element of the container, and so on.","title":"next"},{"location":"reference/math/","text":"Math Built-in mathematical functions. The Math object can be accessed simply by typing Math . Examples: // Math functions two = Math . sqrt ( 4 ); // square root of 4 eight = Math . pow ( 2 , 3 ); // 2 raised to the 3rd power zero = Math . sin ( 0 ); // sine of 0 seven = Math . max ( 5 , 7 ); // maximum of 5 and 7 Properties pi pi : number, read-only. An approximation of pi (3.1415926535...) epsilon epsilon : number, read-only. The difference between 1 and the smallest floating point number that is greater than 1. infinity infinity : number, read-only. A floating point representation of positive infinity. NaN NaN : number, read-only. A numeric data type representing Not-a-Number. Available since: SurgeScript 0.5.3 Functions sqrt sqrt(x) Square root function. Arguments x : number. Returns The square root of x . pow pow(x, p) Raise to power. Arguments x : number. The base. p : number. The exponent. Returns Returns x raised to the p power. exp e(x) Exponential function. Arguments x : number. Returns Returns e raised to the x power. log log(x) Natural logarithm. Arguments x : number. Returns The natural logarithm (base e ) of x . log10 log10(x) Base 10 logarithm. Arguments x : number. Returns The base 10 logarithm of x . sin sin(x) Sine function. Arguments x : number. Angle in radians. Returns The sine of x . cos cos(x) Cosine function. Arguments x : number. Angle in radians. Returns The cosine of x . tan tan(x) Tangent function. Arguments x : number. Angle in radians. Returns The tangent of x . asin asin(x) Arc-sine function. Arguments x : number. Returns The angle in radians whose sine is x . acos acos(x) Arc-cosine function. Arguments x : number. Returns The angle in radians whose cosine is x . atan atan(x) Arc-tangent function. Arguments x : number. Returns The angle in radians whose tangent is x . atan2 atan2(y, x) Function atan2. Arguments y : number. x : number. Returns The angle, in radians, between the positive x-axis and the (x, y) vector. deg2rad deg2rad(degrees) Converts degrees to radians. Available since: SurgeScript 0.5.3 Arguments degrees : number. Returns The converted value. rad2deg rad2deg(radians) Converts radians to degrees. Available since: SurgeScript 0.5.3 Arguments radians : number. Returns The converted value. random random() Random value. Returns A random number between 0 (inclusive) and 1 (exclusive). floor floor(x) Floor function. Arguments x : number. Returns The largest integer less or equal than x . ceil ceil(x) Ceiling function. Arguments x : number. Returns The smallest integer greater or equal than x . round round(x) Round to the nearest integer. Arguments x : number. Returns Returns x rounded to the nearest integer. If the fraction of x is 0.5, this function uses the commercial rounding tie-breaking method. trunc trunc(x) Truncate to integer. Available since: SurgeScript 0.6.0 Arguments x : number. Returns The nearest integer not greater in magnitude than x . mod mod(x, y) Modulo operation. This is used to get the value x mod y - the modulo - defined as the remainder of the division of x by y that has the sign of the divisor y . Info The modulo x mod y may differ from the remainder x % y . The former has the sign of the divisor y , whereas the latter has the sign of the dividend x . When x and y have the same sign, the modulo and the remainder are equal. When the signs differ, modulo and remainder differ by y . Arguments x : number. The dividend. y : number. The divisor. Returns The modulo x mod y . Note The modulo x mod y is returned since SurgeScript 0.6.0. The remainder x % y was returned on SurgeScript 0.5.x. Example x = 5 ; y = 3 ; Console . print ( Math . mod ( x , y )); // 2 Console . print ( x % y ); // 2 Console . print ( Math . mod (- x , - y )); // -2 Console . print (- x % - y ); // -2 Console . print ( Math . mod (- x , y )); // 1 Console . print (- x % y ); // -2 Console . print ( Math . mod ( x , - y )); // -1 Console . print ( x % - y ); // 2 sign sign(x) The sign of x : 1 if x is non-negative, -1 otherwise. Arguments x : number. Returns Returns 1 if x is positive or zero; or -1 if x is negative. signum signum(x) Function signum( x ) returns 1 if x is positive, 0 if is x is zero, or -1 if x is negative. Available since: SurgeScript 0.5.4 Arguments x : number. Returns Returns 1 if x is positive, 0 if is x is zero, or -1 if x is negative. abs abs(x) Absolute value of x . Arguments x : number. Returns Returns -x if x is negative, or x otherwise. min min(x, y) The minimum of two values. Arguments x : number. y : number. Returns Returns the minimum of x and y . max max(x, y) The maximum of two values. Arguments x : number. y : number. Returns Returns the maximum of x and y . clamp clamp(val, min, max) Clamps a value between a minimum and a maximum. Arguments val : number. The value to be clamped. min : number. Minimum value. max : number. Maximum value. Returns Returns val clamped between min and max . Function clamp behave as follows: if val < min , it returns min if val > max , it returns max otherwise, it returns val approximately approximately(x, y) Compares two floating point values. Since comparing two floating point numbers for equality directly may result in inaccuracies, this is a handy function. Arguments x : number. y : number. Returns Returns true if x and y are \"approximately\" equal. lerp lerp(a, b, t) Linear interpolation. Arguments a : number. b : number. t : number. A value between 0 and 1. Returns Returns the linear interpolation between a and b by t . Value t is clamped automatically to the [0, 1] range. As an example, note that lerp : returns a if t is 0 returns b if t is 1 returns (a + b) / 2 if t is 0.5 smoothstep smoothstep(a, b, t) Interpolation smoothing at the limits. Arguments a : number. b : number. t : number. A value between 0 and 1. Returns Returns an interpolated value between a and b by t . Unlike lerp , smoothstep is smooth at the limits. This is useful to create smooth transitions and animations. Value t is clamped automatically to the [0, 1] range. lerpAngle lerpAngle(alpha, beta, t) Linear interpolation of angles alpha and beta given in degrees. Unlike lerp , lerpAngle can interpolate angles when they wrap around 360 degrees. Available since: SurgeScript 0.5.4.1 Arguments alpha : number. A value in degrees. beta : number. A value in degrees. t : number. A value between 0 and 1. Returns Returns the linear interpolation between angles alpha and beta , given in degrees, by t . deltaAngle deltaAngle(alpha, beta) The shortest difference between angles alpha and beta given in degrees. Available since: SurgeScript 0.5.4.1 Arguments alpha : number. A value in degrees. beta : number. A value in degrees. Returns Returns, in degrees, the shortest difference between the angles.","title":"Math"},{"location":"reference/math/#math","text":"Built-in mathematical functions. The Math object can be accessed simply by typing Math . Examples: // Math functions two = Math . sqrt ( 4 ); // square root of 4 eight = Math . pow ( 2 , 3 ); // 2 raised to the 3rd power zero = Math . sin ( 0 ); // sine of 0 seven = Math . max ( 5 , 7 ); // maximum of 5 and 7","title":"Math"},{"location":"reference/math/#properties","text":"","title":"Properties"},{"location":"reference/math/#pi","text":"pi : number, read-only. An approximation of pi (3.1415926535...)","title":"pi"},{"location":"reference/math/#epsilon","text":"epsilon : number, read-only. The difference between 1 and the smallest floating point number that is greater than 1.","title":"epsilon"},{"location":"reference/math/#infinity","text":"infinity : number, read-only. A floating point representation of positive infinity.","title":"infinity"},{"location":"reference/math/#nan","text":"NaN : number, read-only. A numeric data type representing Not-a-Number. Available since: SurgeScript 0.5.3","title":"NaN"},{"location":"reference/math/#functions","text":"","title":"Functions"},{"location":"reference/math/#sqrt","text":"sqrt(x) Square root function. Arguments x : number. Returns The square root of x .","title":"sqrt"},{"location":"reference/math/#pow","text":"pow(x, p) Raise to power. Arguments x : number. The base. p : number. The exponent. Returns Returns x raised to the p power.","title":"pow"},{"location":"reference/math/#exp","text":"e(x) Exponential function. Arguments x : number. Returns Returns e raised to the x power.","title":"exp"},{"location":"reference/math/#log","text":"log(x) Natural logarithm. Arguments x : number. Returns The natural logarithm (base e ) of x .","title":"log"},{"location":"reference/math/#log10","text":"log10(x) Base 10 logarithm. Arguments x : number. Returns The base 10 logarithm of x .","title":"log10"},{"location":"reference/math/#sin","text":"sin(x) Sine function. Arguments x : number. Angle in radians. Returns The sine of x .","title":"sin"},{"location":"reference/math/#cos","text":"cos(x) Cosine function. Arguments x : number. Angle in radians. Returns The cosine of x .","title":"cos"},{"location":"reference/math/#tan","text":"tan(x) Tangent function. Arguments x : number. Angle in radians. Returns The tangent of x .","title":"tan"},{"location":"reference/math/#asin","text":"asin(x) Arc-sine function. Arguments x : number. Returns The angle in radians whose sine is x .","title":"asin"},{"location":"reference/math/#acos","text":"acos(x) Arc-cosine function. Arguments x : number. Returns The angle in radians whose cosine is x .","title":"acos"},{"location":"reference/math/#atan","text":"atan(x) Arc-tangent function. Arguments x : number. Returns The angle in radians whose tangent is x .","title":"atan"},{"location":"reference/math/#atan2","text":"atan2(y, x) Function atan2. Arguments y : number. x : number. Returns The angle, in radians, between the positive x-axis and the (x, y) vector.","title":"atan2"},{"location":"reference/math/#deg2rad","text":"deg2rad(degrees) Converts degrees to radians. Available since: SurgeScript 0.5.3 Arguments degrees : number. Returns The converted value.","title":"deg2rad"},{"location":"reference/math/#rad2deg","text":"rad2deg(radians) Converts radians to degrees. Available since: SurgeScript 0.5.3 Arguments radians : number. Returns The converted value.","title":"rad2deg"},{"location":"reference/math/#random","text":"random() Random value. Returns A random number between 0 (inclusive) and 1 (exclusive).","title":"random"},{"location":"reference/math/#floor","text":"floor(x) Floor function. Arguments x : number. Returns The largest integer less or equal than x .","title":"floor"},{"location":"reference/math/#ceil","text":"ceil(x) Ceiling function. Arguments x : number. Returns The smallest integer greater or equal than x .","title":"ceil"},{"location":"reference/math/#round","text":"round(x) Round to the nearest integer. Arguments x : number. Returns Returns x rounded to the nearest integer. If the fraction of x is 0.5, this function uses the commercial rounding tie-breaking method.","title":"round"},{"location":"reference/math/#trunc","text":"trunc(x) Truncate to integer. Available since: SurgeScript 0.6.0 Arguments x : number. Returns The nearest integer not greater in magnitude than x .","title":"trunc"},{"location":"reference/math/#mod","text":"mod(x, y) Modulo operation. This is used to get the value x mod y - the modulo - defined as the remainder of the division of x by y that has the sign of the divisor y . Info The modulo x mod y may differ from the remainder x % y . The former has the sign of the divisor y , whereas the latter has the sign of the dividend x . When x and y have the same sign, the modulo and the remainder are equal. When the signs differ, modulo and remainder differ by y . Arguments x : number. The dividend. y : number. The divisor. Returns The modulo x mod y . Note The modulo x mod y is returned since SurgeScript 0.6.0. The remainder x % y was returned on SurgeScript 0.5.x. Example x = 5 ; y = 3 ; Console . print ( Math . mod ( x , y )); // 2 Console . print ( x % y ); // 2 Console . print ( Math . mod (- x , - y )); // -2 Console . print (- x % - y ); // -2 Console . print ( Math . mod (- x , y )); // 1 Console . print (- x % y ); // -2 Console . print ( Math . mod ( x , - y )); // -1 Console . print ( x % - y ); // 2","title":"mod"},{"location":"reference/math/#sign","text":"sign(x) The sign of x : 1 if x is non-negative, -1 otherwise. Arguments x : number. Returns Returns 1 if x is positive or zero; or -1 if x is negative.","title":"sign"},{"location":"reference/math/#signum","text":"signum(x) Function signum( x ) returns 1 if x is positive, 0 if is x is zero, or -1 if x is negative. Available since: SurgeScript 0.5.4 Arguments x : number. Returns Returns 1 if x is positive, 0 if is x is zero, or -1 if x is negative.","title":"signum"},{"location":"reference/math/#abs","text":"abs(x) Absolute value of x . Arguments x : number. Returns Returns -x if x is negative, or x otherwise.","title":"abs"},{"location":"reference/math/#min","text":"min(x, y) The minimum of two values. Arguments x : number. y : number. Returns Returns the minimum of x and y .","title":"min"},{"location":"reference/math/#max","text":"max(x, y) The maximum of two values. Arguments x : number. y : number. Returns Returns the maximum of x and y .","title":"max"},{"location":"reference/math/#clamp","text":"clamp(val, min, max) Clamps a value between a minimum and a maximum. Arguments val : number. The value to be clamped. min : number. Minimum value. max : number. Maximum value. Returns Returns val clamped between min and max . Function clamp behave as follows: if val < min , it returns min if val > max , it returns max otherwise, it returns val","title":"clamp"},{"location":"reference/math/#approximately","text":"approximately(x, y) Compares two floating point values. Since comparing two floating point numbers for equality directly may result in inaccuracies, this is a handy function. Arguments x : number. y : number. Returns Returns true if x and y are \"approximately\" equal.","title":"approximately"},{"location":"reference/math/#lerp","text":"lerp(a, b, t) Linear interpolation. Arguments a : number. b : number. t : number. A value between 0 and 1. Returns Returns the linear interpolation between a and b by t . Value t is clamped automatically to the [0, 1] range. As an example, note that lerp : returns a if t is 0 returns b if t is 1 returns (a + b) / 2 if t is 0.5","title":"lerp"},{"location":"reference/math/#smoothstep","text":"smoothstep(a, b, t) Interpolation smoothing at the limits. Arguments a : number. b : number. t : number. A value between 0 and 1. Returns Returns an interpolated value between a and b by t . Unlike lerp , smoothstep is smooth at the limits. This is useful to create smooth transitions and animations. Value t is clamped automatically to the [0, 1] range.","title":"smoothstep"},{"location":"reference/math/#lerpangle","text":"lerpAngle(alpha, beta, t) Linear interpolation of angles alpha and beta given in degrees. Unlike lerp , lerpAngle can interpolate angles when they wrap around 360 degrees. Available since: SurgeScript 0.5.4.1 Arguments alpha : number. A value in degrees. beta : number. A value in degrees. t : number. A value between 0 and 1. Returns Returns the linear interpolation between angles alpha and beta , given in degrees, by t .","title":"lerpAngle"},{"location":"reference/math/#deltaangle","text":"deltaAngle(alpha, beta) The shortest difference between angles alpha and beta given in degrees. Available since: SurgeScript 0.5.4.1 Arguments alpha : number. A value in degrees. beta : number. A value in degrees. Returns Returns, in degrees, the shortest difference between the angles.","title":"deltaAngle"},{"location":"reference/number/","text":"Number Routines for numbers. The Number object is not supposed to be used directly. The functions below are available for primitive values of the number type. Example: x = 2. toString (); // x is \"2\" t = typeof ( x ); // t is \"string\" Note: the SurgeScript Runtime stores numbers as 64-bit floating point values (following the IEEE 754 standard). Integer numbers are accurate up to 15 digits. Functions valueOf valueOf() The primitive value of the number, i.e., the number itself. Returns The number. toString toString() Converts the number to a string. Returns The number converted to a string. equals equals(x) Compares the number to another number x . This routine performs a comparison between floating point numbers. It's recommended to use Math.approximately() instead. Arguments x : number. The value to compare the number to. Returns Returns true if the numbers are equal. isFinite isFinite() Checks if the number is finite. Available since: SurgeScript 0.5.2 Returns Returns true if the number is finite. isNaN isNaN() Checks if the value is NaN (Not-a-Number). Available since: SurgeScript 0.5.2 Returns Returns true if the value is NaN. isInteger isInteger() Checks if the number is an integer. Available since: SurgeScript 0.5.2 Returns Returns true if the number is an integer.","title":"Number"},{"location":"reference/number/#number","text":"Routines for numbers. The Number object is not supposed to be used directly. The functions below are available for primitive values of the number type. Example: x = 2. toString (); // x is \"2\" t = typeof ( x ); // t is \"string\" Note: the SurgeScript Runtime stores numbers as 64-bit floating point values (following the IEEE 754 standard). Integer numbers are accurate up to 15 digits.","title":"Number"},{"location":"reference/number/#functions","text":"","title":"Functions"},{"location":"reference/number/#valueof","text":"valueOf() The primitive value of the number, i.e., the number itself. Returns The number.","title":"valueOf"},{"location":"reference/number/#tostring","text":"toString() Converts the number to a string. Returns The number converted to a string.","title":"toString"},{"location":"reference/number/#equals","text":"equals(x) Compares the number to another number x . This routine performs a comparison between floating point numbers. It's recommended to use Math.approximately() instead. Arguments x : number. The value to compare the number to. Returns Returns true if the numbers are equal.","title":"equals"},{"location":"reference/number/#isfinite","text":"isFinite() Checks if the number is finite. Available since: SurgeScript 0.5.2 Returns Returns true if the number is finite.","title":"isFinite"},{"location":"reference/number/#isnan","text":"isNaN() Checks if the value is NaN (Not-a-Number). Available since: SurgeScript 0.5.2 Returns Returns true if the value is NaN.","title":"isNaN"},{"location":"reference/number/#isinteger","text":"isInteger() Checks if the number is an integer. Available since: SurgeScript 0.5.2 Returns Returns true if the number is an integer.","title":"isInteger"},{"location":"reference/object/","text":"Object In SurgeScript, all objects are also instances of Object . This means that the properties and functions listed below are available for all objects: Properties parent parent : object, read-only. Reference to the parent object. __name __name : string, read-only. The name of the object. __active __active : boolean. Indicates whether the object is active or not. Objects are active by default. Whenever an object is set to be inactive, its state machine is paused. Additionally, the state machines of all its descendants are also paused. __functions __functions : Array object, read-only. The functions of this object represented as a collection of strings. __timespent __timespent : number, read-only. The average time spent in the current state (measured in seconds). __file __file : string, read-only. The source file of this object. Available since: SurgeScript 0.5.3 __children __children : Array object, read-only. The children of this object. Available since: SurgeScript 0.5.4 Returns A new array featuring all the children of this object. If there are no children, an empty array is returned. __childCount __childCount : number, read-only. The number of children of the object. Available since: SurgeScript 0.5.5 Note: prior to SurgeScript 0.5.5, you would use object.childCount instead. That form is now obsolete. Functions spawn spawn(objectName) Spawns an object named objectName . Arguments objectName : string. The name of the object to be spawned / instantiated. Returns A new object of the desired name. Note that the newly created object will be a child of this . destroy destroy() Destroys the object. child child(childName | childId) Looks for a child named childName (or matching childId ). Arguments childName : string. The name of the desired child. childId : number. The id of the desired child, an integer between 0 and childCount - 1 , inclusive. Returns The desired child, or null if there is no such object. children children(childName) Finds all children named childName . Since this function spawns a new array at each call, it's recommended to cache its return value. Available since: SurgeScript 0.5.4 Arguments childName : string. The name of the desired children. Returns A new array containing all children named childName . If no such children are found, an empty array is returned. childWithTag childWithTag(tagName) Finds a child tagged tagName . Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A child tagged tagName , or null if there is no such object. childrenWithTag childrenWithTag(tagName) Finds all children tagged tagName . Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A new array containing all children tagged tagName . If there are no such children, an empty array is returned. sibling sibling(siblingName) Looks for a sibling named siblingName . Two objects are siblings if they share the same parent. Arguments siblingName : string. The name of the desired sibling. Returns A sibling of name siblingName , or null if there is no such object. findObject findObject(objectName) Finds a descendant (child, grand-child, and so on) named objectName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Arguments objectName : string. The name of the desired object. Returns A descendant named objectName , or null if there is no such object. Example object \"TestObject\" { // will search for SomeOtherObject in the Application obj = Application . findObject ( \"SomeOtherObject\" ); state \"main\" { if ( obj != null ) Console . print ( \"Found the object.\" ); else Console . print ( \"Object not found.\" ); destroy (); } } findObjects findObjects(objectName) Finds all descendants named objectName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Available since: SurgeScript 0.5.4 Arguments objectName : string. The name of the objects to be found. Returns A new array containing all descendants named objectName . If no such descendants are found, an empty array is returned. findObjectWithTag findObjectWithTag(tagName) Finds a descendant tagged tagName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A descendant tagged tagName , or null if there is no such object. findObjectsWithTag findObjectsWithTag(tagName) Finds all descendants tagged tagName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A new array containing all descendants tagged tagName . If no such descendants are found, an empty array is returned. toString toString() Converts the object to a string. This function is designed to be overloaded by your own objects. Returns A string. equals equals(otherObject) Compares this object to otherObject . This function is designed to be overloaded by your own objects. Arguments otherObject : object. An object to compare this to. Returns Returns true if the objects are equal; false otherwise. hasFunction hasFunction(functionName) Checks if the object has a function named functionName . Arguments functionName : string. The name of the function. Returns Returns true if the object has a function named functionName . hasTag hasTag(tagName) Checks if the object has been tagged tagName . See also: TagSystem.hasTag() . Arguments tagName : string. The name of the tag. Returns Returns true if the object has been tagged tagName . __invoke __invoke(functionName, paramsArray) Invokes function functionName , passing the parameters specified in paramsArray . The number of elements of paramsArray must be the same as the number of parameters required by the function to be invoked. Available since: SurgeScript 0.5.2 Arguments functionName : string. The name of the function to be called. paramsArray : Array . The parameters to be passed to the function. Returns Returns the value returned by the invoked function. Example // The program below will print: // 12 // 12 // true object \"Application\" { state \"main\" { Console . print ( this . sum ( 5 , 7 )); Console . print ( this . __invoke ( \"sum\" , [ 5 , 7 ])); Console . print ( sum ( 5 , 7 ) == __invoke ( \"sum\" , [ 5 , 7 ])); Application . exit (); } fun sum ( a , b ) { return a + b ; } } __arity __arity(functionName) Returns the number of arguments of function functionName , if it's defined. If it's not defined, zero will be returned. Available since: SurgeScript 0.5.4 Arguments functionName : string. The name of a function. Returns The number of arguments of the specified function, or zero if the function is not defined.","title":"Object"},{"location":"reference/object/#object","text":"In SurgeScript, all objects are also instances of Object . This means that the properties and functions listed below are available for all objects:","title":"Object"},{"location":"reference/object/#properties","text":"","title":"Properties"},{"location":"reference/object/#parent","text":"parent : object, read-only. Reference to the parent object.","title":"parent"},{"location":"reference/object/#__name","text":"__name : string, read-only. The name of the object.","title":"__name"},{"location":"reference/object/#__active","text":"__active : boolean. Indicates whether the object is active or not. Objects are active by default. Whenever an object is set to be inactive, its state machine is paused. Additionally, the state machines of all its descendants are also paused.","title":"__active"},{"location":"reference/object/#__functions","text":"__functions : Array object, read-only. The functions of this object represented as a collection of strings.","title":"__functions"},{"location":"reference/object/#__timespent","text":"__timespent : number, read-only. The average time spent in the current state (measured in seconds).","title":"__timespent"},{"location":"reference/object/#__file","text":"__file : string, read-only. The source file of this object. Available since: SurgeScript 0.5.3","title":"__file"},{"location":"reference/object/#__children","text":"__children : Array object, read-only. The children of this object. Available since: SurgeScript 0.5.4 Returns A new array featuring all the children of this object. If there are no children, an empty array is returned.","title":"__children"},{"location":"reference/object/#__childcount","text":"__childCount : number, read-only. The number of children of the object. Available since: SurgeScript 0.5.5 Note: prior to SurgeScript 0.5.5, you would use object.childCount instead. That form is now obsolete.","title":"__childCount"},{"location":"reference/object/#functions","text":"","title":"Functions"},{"location":"reference/object/#spawn","text":"spawn(objectName) Spawns an object named objectName . Arguments objectName : string. The name of the object to be spawned / instantiated. Returns A new object of the desired name. Note that the newly created object will be a child of this .","title":"spawn"},{"location":"reference/object/#destroy","text":"destroy() Destroys the object.","title":"destroy"},{"location":"reference/object/#child","text":"child(childName | childId) Looks for a child named childName (or matching childId ). Arguments childName : string. The name of the desired child. childId : number. The id of the desired child, an integer between 0 and childCount - 1 , inclusive. Returns The desired child, or null if there is no such object.","title":"child"},{"location":"reference/object/#children","text":"children(childName) Finds all children named childName . Since this function spawns a new array at each call, it's recommended to cache its return value. Available since: SurgeScript 0.5.4 Arguments childName : string. The name of the desired children. Returns A new array containing all children named childName . If no such children are found, an empty array is returned.","title":"children"},{"location":"reference/object/#childwithtag","text":"childWithTag(tagName) Finds a child tagged tagName . Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A child tagged tagName , or null if there is no such object.","title":"childWithTag"},{"location":"reference/object/#childrenwithtag","text":"childrenWithTag(tagName) Finds all children tagged tagName . Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A new array containing all children tagged tagName . If there are no such children, an empty array is returned.","title":"childrenWithTag"},{"location":"reference/object/#sibling","text":"sibling(siblingName) Looks for a sibling named siblingName . Two objects are siblings if they share the same parent. Arguments siblingName : string. The name of the desired sibling. Returns A sibling of name siblingName , or null if there is no such object.","title":"sibling"},{"location":"reference/object/#findobject","text":"findObject(objectName) Finds a descendant (child, grand-child, and so on) named objectName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Arguments objectName : string. The name of the desired object. Returns A descendant named objectName , or null if there is no such object. Example object \"TestObject\" { // will search for SomeOtherObject in the Application obj = Application . findObject ( \"SomeOtherObject\" ); state \"main\" { if ( obj != null ) Console . print ( \"Found the object.\" ); else Console . print ( \"Object not found.\" ); destroy (); } }","title":"findObject"},{"location":"reference/object/#findobjects","text":"findObjects(objectName) Finds all descendants named objectName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Available since: SurgeScript 0.5.4 Arguments objectName : string. The name of the objects to be found. Returns A new array containing all descendants named objectName . If no such descendants are found, an empty array is returned.","title":"findObjects"},{"location":"reference/object/#findobjectwithtag","text":"findObjectWithTag(tagName) Finds a descendant tagged tagName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A descendant tagged tagName , or null if there is no such object.","title":"findObjectWithTag"},{"location":"reference/object/#findobjectswithtag","text":"findObjectsWithTag(tagName) Finds all descendants tagged tagName . Since this function traverses the object tree , it's recommended to cache its return value. Do not use it in loops or states, as it might be slow. Available since: SurgeScript 0.5.4 Arguments tagName : string. The name of a tag. Returns A new array containing all descendants tagged tagName . If no such descendants are found, an empty array is returned.","title":"findObjectsWithTag"},{"location":"reference/object/#tostring","text":"toString() Converts the object to a string. This function is designed to be overloaded by your own objects. Returns A string.","title":"toString"},{"location":"reference/object/#equals","text":"equals(otherObject) Compares this object to otherObject . This function is designed to be overloaded by your own objects. Arguments otherObject : object. An object to compare this to. Returns Returns true if the objects are equal; false otherwise.","title":"equals"},{"location":"reference/object/#hasfunction","text":"hasFunction(functionName) Checks if the object has a function named functionName . Arguments functionName : string. The name of the function. Returns Returns true if the object has a function named functionName .","title":"hasFunction"},{"location":"reference/object/#hastag","text":"hasTag(tagName) Checks if the object has been tagged tagName . See also: TagSystem.hasTag() . Arguments tagName : string. The name of the tag. Returns Returns true if the object has been tagged tagName .","title":"hasTag"},{"location":"reference/object/#__invoke","text":"__invoke(functionName, paramsArray) Invokes function functionName , passing the parameters specified in paramsArray . The number of elements of paramsArray must be the same as the number of parameters required by the function to be invoked. Available since: SurgeScript 0.5.2 Arguments functionName : string. The name of the function to be called. paramsArray : Array . The parameters to be passed to the function. Returns Returns the value returned by the invoked function. Example // The program below will print: // 12 // 12 // true object \"Application\" { state \"main\" { Console . print ( this . sum ( 5 , 7 )); Console . print ( this . __invoke ( \"sum\" , [ 5 , 7 ])); Console . print ( sum ( 5 , 7 ) == __invoke ( \"sum\" , [ 5 , 7 ])); Application . exit (); } fun sum ( a , b ) { return a + b ; } }","title":"__invoke"},{"location":"reference/object/#__arity","text":"__arity(functionName) Returns the number of arguments of function functionName , if it's defined. If it's not defined, zero will be returned. Available since: SurgeScript 0.5.4 Arguments functionName : string. The name of a function. Returns The number of arguments of the specified function, or zero if the function is not defined.","title":"__arity"},{"location":"reference/plugin/","text":"Plugin SurgeScript features a plugin system that allows you to extend the functionalities of the language. Known as plugins or packages , these objects can be imported and accessed anywhere in the code. They are imported using a using statement. The plugin system can be accessed simply by typing Plugin . Example: // File: app.ss // An application that uses StringUtils, defined in another file using StringUtils ; object \"Application\" { str = \"alucard\" ; state \"main\" { Console . print ( \"Reverse a string:\" ); Console . print ( str ); Console . print ( StringUtils . reverse ( str )); Application . exit (); } } // File: string_utils.ss // String utilities @Package object \"StringUtils\" { fun reverse ( str ) { buf = \"\" ; for ( i = str . length - 1 ; i >= 0 ; i --) buf += str [ i ]; return buf ; } } Available since: SurgeScript 0.5.2 Properties count count : number, read-only. The number of plugins. Functions spawn spawn(objectName) Spawns an object called objectName as a plugin. This function is not to be used directly, as SurgeScript spawns the plugins automatically for you. Arguments objectName : string. The name of the object to be spawned as a plugin. It's not recommended to include special characters in this name. get get(objectName) Gets a reference to the plugin named objectName . The [ ] operator can be used instead of the get() function, as in Plugin[objectName] . Rather than using this function, it's recommended to import the desired object using the using MyObject; statement at the beginning of your code. Your object will be available as MyObject . Arguments objectName : string. The name of the plugin. Example using StringUtils ; // ... assert ( Plugin [ \"StringUtils\" ] === StringUtils ); assert ( Plugin . StringUtils === StringUtils );","title":"Plugin"},{"location":"reference/plugin/#plugin","text":"SurgeScript features a plugin system that allows you to extend the functionalities of the language. Known as plugins or packages , these objects can be imported and accessed anywhere in the code. They are imported using a using statement. The plugin system can be accessed simply by typing Plugin . Example: // File: app.ss // An application that uses StringUtils, defined in another file using StringUtils ; object \"Application\" { str = \"alucard\" ; state \"main\" { Console . print ( \"Reverse a string:\" ); Console . print ( str ); Console . print ( StringUtils . reverse ( str )); Application . exit (); } } // File: string_utils.ss // String utilities @Package object \"StringUtils\" { fun reverse ( str ) { buf = \"\" ; for ( i = str . length - 1 ; i >= 0 ; i --) buf += str [ i ]; return buf ; } } Available since: SurgeScript 0.5.2","title":"Plugin"},{"location":"reference/plugin/#properties","text":"","title":"Properties"},{"location":"reference/plugin/#count","text":"count : number, read-only. The number of plugins.","title":"count"},{"location":"reference/plugin/#functions","text":"","title":"Functions"},{"location":"reference/plugin/#spawn","text":"spawn(objectName) Spawns an object called objectName as a plugin. This function is not to be used directly, as SurgeScript spawns the plugins automatically for you. Arguments objectName : string. The name of the object to be spawned as a plugin. It's not recommended to include special characters in this name.","title":"spawn"},{"location":"reference/plugin/#get","text":"get(objectName) Gets a reference to the plugin named objectName . The [ ] operator can be used instead of the get() function, as in Plugin[objectName] . Rather than using this function, it's recommended to import the desired object using the using MyObject; statement at the beginning of your code. Your object will be available as MyObject . Arguments objectName : string. The name of the plugin. Example using StringUtils ; // ... assert ( Plugin [ \"StringUtils\" ] === StringUtils ); assert ( Plugin . StringUtils === StringUtils );","title":"get"},{"location":"reference/string/","text":"String Routines for strings. The String object is not supposed to be used directly (generally speaking). The functions below are available for primitive values of the string type. Example: // Useful string routines x = \"SurgeScript\" . toLowerCase (); // \"surgescript\" y = x . substr ( 0 , 5 ); // \"surge\" z = x [ 0 ]; // \"s\" (first character of x) n = y . length ; // 5 Strings in SurgeScript are immutable. Once a string is set, its individual characters cannot be changed. If you need to modify the content of a string, reassign the variable to a new string. Static functions isNullOrEmpty isNullOrEmpty(value) Checks if the given value is either null or an empty string ( \"\" ). Available since: SurgeScript 0.5.3 Arguments value : string | null . The value to be tested. Returns Returns true if value is either null or an empty string. Example name = \"Surge\" ; //name = \"\"; //name = null; if (! String . isNullOrEmpty ( name )) Console . print ( name ); Properties length length : number, read-only. The length of the string. Functions valueOf valueOf() The primitive value of the string, i.e., the string itself. Returns The string. toString toString() Convert to string. Returns The string itself. equals equals(str) Compares the string to another string str . Arguments str : string. Returns Returns true if the strings are equal. get get(i) Gets the i -th character of the string. The [ ] operator can be used equivalently. Arguments i : integer number. A value between 0 (inclusive) and the length of the string (exclusive). Returns The i -th character of the string (0-based index). indexOf indexOf(str) Finds the position of the first occurrence of str in the string. Arguments str : string. The string to be searched for. Returns The position (0-based index) of the first occurrence of str in the string, or -1 if there is no such occurrence. Example name = \"SurgeScript\" ; a = name . indexOf ( \"Surge\" ); // a is 0 b = name . indexOf ( \"Neon\" ); // b is -1 c = name . indexOf ( \"e\" ); // c is 4 d = name . indexOf ( \"script\" ); // d is -1, as the search is case-sensitive substr substr(start, length) Extracts the substring starting at position start with length length . Arguments start : number. The start position. The beginning of the string is at position 0. length : number. The length of the substring. Returns The substring with length length starting at start . Example name = \"SurgeScript\" ; surge = name . substr ( 0 , 5 ); // \"Surge\" script = name . substr ( 5 , 6 ); // \"Script\" e = name . substr ( 4 , 1 ); // \"e\" empty = name . substr ( 555 , 1 ); // \"\" concat concat(str) Concatenates two strings. This is the same as using the + operator. Arguments str : string. Returns The caller string concatenated with str at the end. Example name = \"Surge\" . concat ( \"Script\" ); // SurgeScript name = \"Surge\" + \"Script\" ; // SurgeScript replace replace(oldstr, newstr) Replaces all occurrences of oldstr to newstr in the caller string. Arguments oldstr : string. The substring to be replaced. newstr : string. The substring that should appear in the result. Returns The caller string having all its occurrences of oldstr replaced to newstr . Example // dst is \"Gimacian, Neon and Charge\" src = \"Surge, Neon and Charge\" ; dst = src . replace ( \"Surge\" , \"Gimacian\" ); toLowerCase toLowerCase() Converts the string to lower case. Returns The string converted to lower case. toUpperCase toUpperCase() Converts the string to upper case. Returns The string converted to upper case.","title":"String"},{"location":"reference/string/#string","text":"Routines for strings. The String object is not supposed to be used directly (generally speaking). The functions below are available for primitive values of the string type. Example: // Useful string routines x = \"SurgeScript\" . toLowerCase (); // \"surgescript\" y = x . substr ( 0 , 5 ); // \"surge\" z = x [ 0 ]; // \"s\" (first character of x) n = y . length ; // 5 Strings in SurgeScript are immutable. Once a string is set, its individual characters cannot be changed. If you need to modify the content of a string, reassign the variable to a new string.","title":"String"},{"location":"reference/string/#static-functions","text":"","title":"Static functions"},{"location":"reference/string/#isnullorempty","text":"isNullOrEmpty(value) Checks if the given value is either null or an empty string ( \"\" ). Available since: SurgeScript 0.5.3 Arguments value : string | null . The value to be tested. Returns Returns true if value is either null or an empty string. Example name = \"Surge\" ; //name = \"\"; //name = null; if (! String . isNullOrEmpty ( name )) Console . print ( name );","title":"isNullOrEmpty"},{"location":"reference/string/#properties","text":"","title":"Properties"},{"location":"reference/string/#length","text":"length : number, read-only. The length of the string.","title":"length"},{"location":"reference/string/#functions","text":"","title":"Functions"},{"location":"reference/string/#valueof","text":"valueOf() The primitive value of the string, i.e., the string itself. Returns The string.","title":"valueOf"},{"location":"reference/string/#tostring","text":"toString() Convert to string. Returns The string itself.","title":"toString"},{"location":"reference/string/#equals","text":"equals(str) Compares the string to another string str . Arguments str : string. Returns Returns true if the strings are equal.","title":"equals"},{"location":"reference/string/#get","text":"get(i) Gets the i -th character of the string. The [ ] operator can be used equivalently. Arguments i : integer number. A value between 0 (inclusive) and the length of the string (exclusive). Returns The i -th character of the string (0-based index).","title":"get"},{"location":"reference/string/#indexof","text":"indexOf(str) Finds the position of the first occurrence of str in the string. Arguments str : string. The string to be searched for. Returns The position (0-based index) of the first occurrence of str in the string, or -1 if there is no such occurrence. Example name = \"SurgeScript\" ; a = name . indexOf ( \"Surge\" ); // a is 0 b = name . indexOf ( \"Neon\" ); // b is -1 c = name . indexOf ( \"e\" ); // c is 4 d = name . indexOf ( \"script\" ); // d is -1, as the search is case-sensitive","title":"indexOf"},{"location":"reference/string/#substr","text":"substr(start, length) Extracts the substring starting at position start with length length . Arguments start : number. The start position. The beginning of the string is at position 0. length : number. The length of the substring. Returns The substring with length length starting at start . Example name = \"SurgeScript\" ; surge = name . substr ( 0 , 5 ); // \"Surge\" script = name . substr ( 5 , 6 ); // \"Script\" e = name . substr ( 4 , 1 ); // \"e\" empty = name . substr ( 555 , 1 ); // \"\"","title":"substr"},{"location":"reference/string/#concat","text":"concat(str) Concatenates two strings. This is the same as using the + operator. Arguments str : string. Returns The caller string concatenated with str at the end. Example name = \"Surge\" . concat ( \"Script\" ); // SurgeScript name = \"Surge\" + \"Script\" ; // SurgeScript","title":"concat"},{"location":"reference/string/#replace","text":"replace(oldstr, newstr) Replaces all occurrences of oldstr to newstr in the caller string. Arguments oldstr : string. The substring to be replaced. newstr : string. The substring that should appear in the result. Returns The caller string having all its occurrences of oldstr replaced to newstr . Example // dst is \"Gimacian, Neon and Charge\" src = \"Surge, Neon and Charge\" ; dst = src . replace ( \"Surge\" , \"Gimacian\" );","title":"replace"},{"location":"reference/string/#tolowercase","text":"toLowerCase() Converts the string to lower case. Returns The string converted to lower case.","title":"toLowerCase"},{"location":"reference/string/#touppercase","text":"toUpperCase() Converts the string to upper case. Returns The string converted to upper case.","title":"toUpperCase"},{"location":"reference/surgescript/","text":"SurgeScript Data related to the scripting language itself. You can access this object simply by typing SurgeScript . Example: // Prints the version of the SurgeScript runtime object \"Application\" { state \"main\" { Console . print ( SurgeScript . version ); } } Available since: SurgeScript 0.5.2 Properties version version : string, read-only. Version number of the SurgeScript runtime.","title":"SurgeScript"},{"location":"reference/surgescript/#surgescript","text":"Data related to the scripting language itself. You can access this object simply by typing SurgeScript . Example: // Prints the version of the SurgeScript runtime object \"Application\" { state \"main\" { Console . print ( SurgeScript . version ); } } Available since: SurgeScript 0.5.2","title":"SurgeScript"},{"location":"reference/surgescript/#properties","text":"","title":"Properties"},{"location":"reference/surgescript/#version","text":"version : string, read-only. Version number of the SurgeScript runtime.","title":"version"},{"location":"reference/system/","text":"System The root object. Used to gather data from the language and to access special objects. It can be accessed by typing System . Properties tags tags : Tag System object, read-only. A reference to the Tag System. gc gc : Garbage Collector object, read-only. A reference to the Garbage Collector object. objectCount objectCount : number, read-only. The total number of objects at this moment. Functions exit exit() Exits the Application. destroy destroy() The same as exit() .","title":"System"},{"location":"reference/system/#system","text":"The root object. Used to gather data from the language and to access special objects. It can be accessed by typing System .","title":"System"},{"location":"reference/system/#properties","text":"","title":"Properties"},{"location":"reference/system/#tags","text":"tags : Tag System object, read-only. A reference to the Tag System.","title":"tags"},{"location":"reference/system/#gc","text":"gc : Garbage Collector object, read-only. A reference to the Garbage Collector object.","title":"gc"},{"location":"reference/system/#objectcount","text":"objectCount : number, read-only. The total number of objects at this moment.","title":"objectCount"},{"location":"reference/system/#functions","text":"","title":"Functions"},{"location":"reference/system/#exit","text":"exit() Exits the Application.","title":"exit"},{"location":"reference/system/#destroy","text":"destroy() The same as exit() .","title":"destroy"},{"location":"reference/tags/","text":"TagSystem Utility functions for dealing with object tags. This object is available at System.tags and shouldn't be instantiated directly. Functions list list() Lists all tags used in all objects. Returns A new Array of strings with all tags used in all objects. select select(tagName) Selects all objects that are tagged tagName . Arguments tagName : string. Returns A new Array of strings with the names of the objects tagged with tagName . If there are no such objects, an empty array is returned. tagsOf tagsOf(objectName) Returns the tags of the objects named objectName . Available since: SurgeScript 0.6.0 Arguments objectName : string. Returns A new Array of strings with the names of the tags associated with the objects named objectName . If the objects are untagged or do not exist, an empty array is returned. hasTag hasTag(objectName, tagName) Checks if objects named objectName are tagged tagName . Prefer using Object.hasTag() if possible. See also: Object.hasTag() . Available since: SurgeScript 0.6.0 Arguments objectName : string. tagName : string. Returns Returns true if the objects are tagged as specified, or false otherwise.","title":"TagSystem"},{"location":"reference/tags/#tagsystem","text":"Utility functions for dealing with object tags. This object is available at System.tags and shouldn't be instantiated directly.","title":"TagSystem"},{"location":"reference/tags/#functions","text":"","title":"Functions"},{"location":"reference/tags/#list","text":"list() Lists all tags used in all objects. Returns A new Array of strings with all tags used in all objects.","title":"list"},{"location":"reference/tags/#select","text":"select(tagName) Selects all objects that are tagged tagName . Arguments tagName : string. Returns A new Array of strings with the names of the objects tagged with tagName . If there are no such objects, an empty array is returned.","title":"select"},{"location":"reference/tags/#tagsof","text":"tagsOf(objectName) Returns the tags of the objects named objectName . Available since: SurgeScript 0.6.0 Arguments objectName : string. Returns A new Array of strings with the names of the tags associated with the objects named objectName . If the objects are untagged or do not exist, an empty array is returned.","title":"tagsOf"},{"location":"reference/tags/#hastag","text":"hasTag(objectName, tagName) Checks if objects named objectName are tagged tagName . Prefer using Object.hasTag() if possible. See also: Object.hasTag() . Available since: SurgeScript 0.6.0 Arguments objectName : string. tagName : string. Returns Returns true if the objects are tagged as specified, or false otherwise.","title":"hasTag"},{"location":"reference/time/","text":"Time Time utilities. This object is available simply by typing Time . Properties time time : number, read-only. Elapsed time, in seconds, since the application was started and measured at the beginning of the current frame. delta delta : number, read-only. The time, in seconds, taken to complete the last frame of the application. Use this value to make your application behave consistently regardless of the frame rate. now now : number, read-only. Elapsed time, in seconds, since the application was started and measured at the moment this property is evaluated. Available since: SurgeScript 0.5.4 Tip It's generally advisable to use Time.time instead, because Time.now may return different values in the same frame of your application.","title":"Time"},{"location":"reference/time/#time","text":"Time utilities. This object is available simply by typing Time .","title":"Time"},{"location":"reference/time/#properties","text":"","title":"Properties"},{"location":"reference/time/#time_1","text":"time : number, read-only. Elapsed time, in seconds, since the application was started and measured at the beginning of the current frame.","title":"time"},{"location":"reference/time/#delta","text":"delta : number, read-only. The time, in seconds, taken to complete the last frame of the application. Use this value to make your application behave consistently regardless of the frame rate.","title":"delta"},{"location":"reference/time/#now","text":"now : number, read-only. Elapsed time, in seconds, since the application was started and measured at the moment this property is evaluated. Available since: SurgeScript 0.5.4 Tip It's generally advisable to use Time.time instead, because Time.now may return different values in the same frame of your application.","title":"now"},{"location":"tutorials/advanced_features/","text":"Advanced features This section describes advanced features of SurgeScript. Lookup operator Some programming languages, such as C++, have a feature called operator overloading . It's a syntactic sugar that allows the programmer to attribute custom implementations to different operators. In SurgeScript, the [] operator (also called the lookup operator ), used by Arrays and Dictionaries , is used to get and set values from/to the data structure. In fact, the [] operator can be used with any object. It is necessary to define, in your object, functions named get() and set() with the following signature: fun get ( key ) { // custom implementation } fun set ( key , value ) { // custom implementation } Given an object obj , the expression x = obj[key] is equivalent to x = obj.get(key) . Similarly, obj[key] = value is equivalent to obj.set(key, value) . Function objects In SurgeScript, objects can be made to behave like functions. We call these objects function objects (or functors ). To make an object behave like a function, you have to overload the () operator (also known as the function operator ). This is done by defining function call() in your object: fun call () { // custom implementation } Function call() may take any number of parameters. Given an object f , the expression y = f(x) is equivalent to y = f.call(x) . Notice that, since f is an object, you may exchange its implementation during runtime. Assertions The assert(condition) statement specifies a condition that you expect to be true at a certain point in your code. If that condition turns out to be false, the code will be interrupted with an assertion failed error. Example: assert ( name == \"Surge\" ); // will crash if name isn't \"Surge\" Chaining In SurgeScript, it's possible to configure objects in an elegant way using a technique called chaining . Consider the object below - it simply displays a message at regular intervals: object \"Parrot\" { message = \"I am a Parrot\" ; state \"main\" { if ( timeout ( 1.0 )) state = \"print\" ; } state \"print\" { Console . print ( message ); state = \"main\" ; } // Note that this function returns // this, i.e., the object itself. fun setMessage ( newMessage ) { message = newMessage ; return this ; } } Suppose that, in your Application, you would like to spawn that object and modify its message. One way of doing it would be making its internal variable public and changing its contents in the constructor function of your Application. A more concise and elegant way of doing it would be calling function setMessage() just after you spawn the object: object \"Application\" { parrot = spawn ( \"Parrot\" ). setMessage ( \"Hello!\" ); state \"main\" { } } Observe that the function we have defined does two things: It modifies the internals of the object in some way It always returns this (that is, the object itself) We call that function a chainable function . You may call such a function from your Application, just after spawn() , and you'll still have a reference to the spawned object. Moreover, since chainable functions always return this , you may chain multiple function calls into a single statement, making your code concise and your statement descriptive. Example: parrot = spawn ( \"Parrot\" ). setMessage ( \"Hello!\" ). setInterval ( 2.0 ); Factory In SurgeScript, a factory is a functor that spawns an object for you. The object can be spawned and configured in a single call. In the example below, factory Greeter spawns and configures Greeting objects. We annotate the factory with @Package , so it can be imported anywhere in the code. To the end-user, calling Greeter() is simpler than manually spawning and configuring a Greeting every time it is needed. // Factory example using Greeter ; // import the factory object \"Application\" { state \"main\" { // This will print: // Hello, alex! g = Greeter ( \"alex\" ); g . greet (); exit (); } } // File: greeting.ss object \"Greeting\" { public name = \"anon\" ; fun greet () { Console . print ( \"Hello, \" + name + \"!\" ); } } @Package object \"Greeter\" { // Greeter is a factory. It spawns and configures // a Greeting object for you. As it is a package, // it can be imported and used anywhere. fun call ( name ) { g = spawn ( \"Greeting\" ); g . name = name ; return g ; } } In the example above, objects spawned by the factory will be children of the factory. If you need the parent of the spawned object to be the caller, simply write g = caller.spawn(\"Greeter\") . Know that caller points to the object that called the function (or null if not applicable). Iterators As seen in the loops section, the foreach loop may be used to iterate through an iterable collection. In SurgeScript, an iterable collection is an object that implements the iterator protocol described below. You may implement your own iterable collections by tagging them as \"iterable\" and implementing function iterator() . If you have ever used Java, you'll find this to be familiar. // Iterable collections are tagged \"iterable\" // and implement function iterator() object \"MyCollection\" is \"iterable\" { fun iterator () { // function iterator() takes no arguments and // returns a new iterator object } } For each iterable collection you define, you must define its iterator object. The iterator object must be tagged \"iterator\" and implement functions next() and hasNext() (both take no arguments): // Iterators are tagged \"iterator\" and // implement functions next() and hasNext() object \"MyIterator\" is \"iterator\" { fun next () { // returns the next element of the collection // and advances the iteration pointer // the iterable collection is usually the parent // object, i.e., collection = parent } function hasNext () { // returns true if the enumeration isn't over // returns false if there are no more elements } } You may iterate over an iterable collection using the following code: it = collection . iterator (); while ( it . hasNext ()) { x = it . next (); // do something with x // x is an element of the collection Console . print ( x ); } Or, alternatively, using the compact foreach: foreach ( x in collection ) { Console . print ( x ); } For the sake of completion, the following code demonstrates how to implement a custom iterable collection that hold even numbers from 0 up to 20 without having to store them explicitly in memory: object \"Application\" { evenNumbers = spawn ( \"Even Numbers\" ). upTo ( 20 ); state \"main\" { // print all the numbers of the iterable collection foreach ( number in evenNumbers ) Console . print ( number ); // we're done! exit (); } } object \"Even Numbers\" is \"iterable\" { lastNumber = 0 ; fun iterator () { return spawn ( \"Even Numbers Iterator\" ). upTo ( lastNumber ); } fun upTo ( num ) { // upTo() is a chainable function that // is NOT part of the iterator protocol // (but it's useful for this example) lastNumber = Number ( num ); return this ; } } object \"Even Numbers Iterator\" is \"iterator\" { nextNumber = 0 ; lastNumber = 0 ; fun next () { currentNumber = nextNumber ; nextNumber += 2 ; return currentNumber ; } fun hasNext () { return nextNumber <= lastNumber ; } fun upTo ( num ) { // upTo() is a chainable function that // is NOT part of the iterator protocol // (but it's useful for this example) lastNumber = Number ( num ); return this ; } } The output of this code is: 0 2 4 6 8 10 12 14 16 18 20 Challenge! Can you write an iterable collection called Fibonacci Sequence containing the first N Fibonacci numbers without storing them all explicitly in memory? It should be used as follows: // Desired output (for N=10): 0 1 1 2 3 5 8 13 21 34 sequence = spawn ( \"Fibonacci Sequence\" ). ofLength ( 10 ); foreach ( number in sequence ) Console . print ( number );","title":"Advanced features"},{"location":"tutorials/advanced_features/#advanced-features","text":"This section describes advanced features of SurgeScript.","title":"Advanced features"},{"location":"tutorials/advanced_features/#lookup-operator","text":"Some programming languages, such as C++, have a feature called operator overloading . It's a syntactic sugar that allows the programmer to attribute custom implementations to different operators. In SurgeScript, the [] operator (also called the lookup operator ), used by Arrays and Dictionaries , is used to get and set values from/to the data structure. In fact, the [] operator can be used with any object. It is necessary to define, in your object, functions named get() and set() with the following signature: fun get ( key ) { // custom implementation } fun set ( key , value ) { // custom implementation } Given an object obj , the expression x = obj[key] is equivalent to x = obj.get(key) . Similarly, obj[key] = value is equivalent to obj.set(key, value) .","title":"Lookup operator"},{"location":"tutorials/advanced_features/#function-objects","text":"In SurgeScript, objects can be made to behave like functions. We call these objects function objects (or functors ). To make an object behave like a function, you have to overload the () operator (also known as the function operator ). This is done by defining function call() in your object: fun call () { // custom implementation } Function call() may take any number of parameters. Given an object f , the expression y = f(x) is equivalent to y = f.call(x) . Notice that, since f is an object, you may exchange its implementation during runtime.","title":"Function objects"},{"location":"tutorials/advanced_features/#assertions","text":"The assert(condition) statement specifies a condition that you expect to be true at a certain point in your code. If that condition turns out to be false, the code will be interrupted with an assertion failed error. Example: assert ( name == \"Surge\" ); // will crash if name isn't \"Surge\"","title":"Assertions"},{"location":"tutorials/advanced_features/#chaining","text":"In SurgeScript, it's possible to configure objects in an elegant way using a technique called chaining . Consider the object below - it simply displays a message at regular intervals: object \"Parrot\" { message = \"I am a Parrot\" ; state \"main\" { if ( timeout ( 1.0 )) state = \"print\" ; } state \"print\" { Console . print ( message ); state = \"main\" ; } // Note that this function returns // this, i.e., the object itself. fun setMessage ( newMessage ) { message = newMessage ; return this ; } } Suppose that, in your Application, you would like to spawn that object and modify its message. One way of doing it would be making its internal variable public and changing its contents in the constructor function of your Application. A more concise and elegant way of doing it would be calling function setMessage() just after you spawn the object: object \"Application\" { parrot = spawn ( \"Parrot\" ). setMessage ( \"Hello!\" ); state \"main\" { } } Observe that the function we have defined does two things: It modifies the internals of the object in some way It always returns this (that is, the object itself) We call that function a chainable function . You may call such a function from your Application, just after spawn() , and you'll still have a reference to the spawned object. Moreover, since chainable functions always return this , you may chain multiple function calls into a single statement, making your code concise and your statement descriptive. Example: parrot = spawn ( \"Parrot\" ). setMessage ( \"Hello!\" ). setInterval ( 2.0 );","title":"Chaining"},{"location":"tutorials/advanced_features/#factory","text":"In SurgeScript, a factory is a functor that spawns an object for you. The object can be spawned and configured in a single call. In the example below, factory Greeter spawns and configures Greeting objects. We annotate the factory with @Package , so it can be imported anywhere in the code. To the end-user, calling Greeter() is simpler than manually spawning and configuring a Greeting every time it is needed. // Factory example using Greeter ; // import the factory object \"Application\" { state \"main\" { // This will print: // Hello, alex! g = Greeter ( \"alex\" ); g . greet (); exit (); } } // File: greeting.ss object \"Greeting\" { public name = \"anon\" ; fun greet () { Console . print ( \"Hello, \" + name + \"!\" ); } } @Package object \"Greeter\" { // Greeter is a factory. It spawns and configures // a Greeting object for you. As it is a package, // it can be imported and used anywhere. fun call ( name ) { g = spawn ( \"Greeting\" ); g . name = name ; return g ; } } In the example above, objects spawned by the factory will be children of the factory. If you need the parent of the spawned object to be the caller, simply write g = caller.spawn(\"Greeter\") . Know that caller points to the object that called the function (or null if not applicable).","title":"Factory"},{"location":"tutorials/advanced_features/#iterators","text":"As seen in the loops section, the foreach loop may be used to iterate through an iterable collection. In SurgeScript, an iterable collection is an object that implements the iterator protocol described below. You may implement your own iterable collections by tagging them as \"iterable\" and implementing function iterator() . If you have ever used Java, you'll find this to be familiar. // Iterable collections are tagged \"iterable\" // and implement function iterator() object \"MyCollection\" is \"iterable\" { fun iterator () { // function iterator() takes no arguments and // returns a new iterator object } } For each iterable collection you define, you must define its iterator object. The iterator object must be tagged \"iterator\" and implement functions next() and hasNext() (both take no arguments): // Iterators are tagged \"iterator\" and // implement functions next() and hasNext() object \"MyIterator\" is \"iterator\" { fun next () { // returns the next element of the collection // and advances the iteration pointer // the iterable collection is usually the parent // object, i.e., collection = parent } function hasNext () { // returns true if the enumeration isn't over // returns false if there are no more elements } } You may iterate over an iterable collection using the following code: it = collection . iterator (); while ( it . hasNext ()) { x = it . next (); // do something with x // x is an element of the collection Console . print ( x ); } Or, alternatively, using the compact foreach: foreach ( x in collection ) { Console . print ( x ); } For the sake of completion, the following code demonstrates how to implement a custom iterable collection that hold even numbers from 0 up to 20 without having to store them explicitly in memory: object \"Application\" { evenNumbers = spawn ( \"Even Numbers\" ). upTo ( 20 ); state \"main\" { // print all the numbers of the iterable collection foreach ( number in evenNumbers ) Console . print ( number ); // we're done! exit (); } } object \"Even Numbers\" is \"iterable\" { lastNumber = 0 ; fun iterator () { return spawn ( \"Even Numbers Iterator\" ). upTo ( lastNumber ); } fun upTo ( num ) { // upTo() is a chainable function that // is NOT part of the iterator protocol // (but it's useful for this example) lastNumber = Number ( num ); return this ; } } object \"Even Numbers Iterator\" is \"iterator\" { nextNumber = 0 ; lastNumber = 0 ; fun next () { currentNumber = nextNumber ; nextNumber += 2 ; return currentNumber ; } fun hasNext () { return nextNumber <= lastNumber ; } fun upTo ( num ) { // upTo() is a chainable function that // is NOT part of the iterator protocol // (but it's useful for this example) lastNumber = Number ( num ); return this ; } } The output of this code is: 0 2 4 6 8 10 12 14 16 18 20 Challenge! Can you write an iterable collection called Fibonacci Sequence containing the first N Fibonacci numbers without storing them all explicitly in memory? It should be used as follows: // Desired output (for N=10): 0 1 1 2 3 5 8 13 21 34 sequence = spawn ( \"Fibonacci Sequence\" ). ofLength ( 10 ); foreach ( number in sequence ) Console . print ( number );","title":"Iterators"},{"location":"tutorials/best_practices/","text":"Best Practices Read the Components section. It's crucial that you understand it. Follow the golden rule: objects should not mess with each others' internals! Objects should not change others' internal variables or states directly (not allowed!) Objects should define functions that can be operated upon by the external world (API) Use a consistent coding style. Suggestion: Use camelCase names for both variables and functions. Use 4 spaces when indenting your code. Combine related packages into a single one: don't pollute the global namespace. Read the SurgeScript documentation often. Practice, practice, practice! - and have fun!","title":"Best practices"},{"location":"tutorials/best_practices/#best-practices","text":"Read the Components section. It's crucial that you understand it. Follow the golden rule: objects should not mess with each others' internals! Objects should not change others' internal variables or states directly (not allowed!) Objects should define functions that can be operated upon by the external world (API) Use a consistent coding style. Suggestion: Use camelCase names for both variables and functions. Use 4 spaces when indenting your code. Combine related packages into a single one: don't pollute the global namespace. Read the SurgeScript documentation often. Practice, practice, practice! - and have fun!","title":"Best Practices"},{"location":"tutorials/comments/","text":"Comments Comments are used to make your code more human-readable. They are ignored by the computer. SurgeScript allows two kinds of comments: single-line comments and multi-line comments. Single-line comments Single-line comments start with a // . Example: // This line has no effect on the code (it's just for improved readability) x = 3 + 4 ; // x is now 7 Multi-line comments Multi-line comments start with a /* and end with a */ . Example: /* * Comments can, but don't have to, take * multiple lines if you use this form. */ x = 3 + 4 ; /* x is now 7 */ Comments of this form cannot be nested.","title":"Comments"},{"location":"tutorials/comments/#comments","text":"Comments are used to make your code more human-readable. They are ignored by the computer. SurgeScript allows two kinds of comments: single-line comments and multi-line comments.","title":"Comments"},{"location":"tutorials/comments/#single-line-comments","text":"Single-line comments start with a // . Example: // This line has no effect on the code (it's just for improved readability) x = 3 + 4 ; // x is now 7","title":"Single-line comments"},{"location":"tutorials/comments/#multi-line-comments","text":"Multi-line comments start with a /* and end with a */ . Example: /* * Comments can, but don't have to, take * multiple lines if you use this form. */ x = 3 + 4 ; /* x is now 7 */ Comments of this form cannot be nested.","title":"Multi-line comments"},{"location":"tutorials/components/","text":"Components Introduction Entity Component System (ECS) is a software pattern used in game development. The idea is that in-game objects (called entities ) can be customized by adding or removing objects (called components ) during runtime. Components add functionalities or behaviors to the entities to which they are attached to. In SurgeScript, both entities and components are objects - the difference is conceptual. As an example, consider an in-game object called Parrot . Objects by themselves are empty; they do nothing. However, an interesting behavior of parrots is that they are blabbers: they keep repeating the same thing over and over again. So, let's create an empty object called Parrot , tag it as an entity and spawn the Blabber component on it: object \"Parrot\" is \"entity\" { blabber = spawn ( \"Blabber\" ); state \"main\" { } } object \"Blabber\" { state \"main\" { if ( timeout ( 2 )) // blab every 2 seconds state = \"blab\" ; } state \"blab\" { Console . print ( \"Hello!\" ); state = \"main\" ; } } Now, whenever you spawn a Parrot, it will keep blabbing ( parroting ) unceasingly: Hello! Hello! Hello! ... Suppose now that your Parrot is a Kamikaze Robot: it blabs so much that it will explode itself after some time. We'll attach a Time Bomb to the parroting robot, so that it will stop blabbing after a while: object \"Time Bomb\" { state \"main\" { if ( timeout ( 15 )) // explode after 15 seconds state = \"explode\" ; } state \"explode\" { Console . print ( \"BOOOM!\" ); parent . destroy (); // destroy the parent object } } object \"Parrot\" is \"entity\" { blabber = spawn ( \"Blabber\" ); bomb = spawn ( \"Time Bomb\" ); state \"main\" { } } Now, here's the output: Hello! Hello! Hello! Hello! Hello! Hello! Hello! BOOOM! In this example, Parrot is an entity and Blabber and Time Bomb are its components. Once the entity is destroyed, its components (its children) are also destroyed automatically. Design considerations In some implementations of ECS, entities are implemented as integers and components consist of raw data only. The game logic is executed by the System layer, which iterates throughout all entities continuously and executes the logic according to the components attached to them. In SurgeScript, components execute their own code and can be attached to entities simply by spawning them as children. Still, you can use the former approach if you wish to do so. Composition over inheritance SurgeScript does not explicitly support inheritance, a feature found in other object-oriented languages. The usage of components is encouraged instead. SurgeScript favors composition over inheritance, allowing for greater flexibility when defining in-game objects.","title":"Components"},{"location":"tutorials/components/#components","text":"","title":"Components"},{"location":"tutorials/components/#introduction","text":"Entity Component System (ECS) is a software pattern used in game development. The idea is that in-game objects (called entities ) can be customized by adding or removing objects (called components ) during runtime. Components add functionalities or behaviors to the entities to which they are attached to. In SurgeScript, both entities and components are objects - the difference is conceptual. As an example, consider an in-game object called Parrot . Objects by themselves are empty; they do nothing. However, an interesting behavior of parrots is that they are blabbers: they keep repeating the same thing over and over again. So, let's create an empty object called Parrot , tag it as an entity and spawn the Blabber component on it: object \"Parrot\" is \"entity\" { blabber = spawn ( \"Blabber\" ); state \"main\" { } } object \"Blabber\" { state \"main\" { if ( timeout ( 2 )) // blab every 2 seconds state = \"blab\" ; } state \"blab\" { Console . print ( \"Hello!\" ); state = \"main\" ; } } Now, whenever you spawn a Parrot, it will keep blabbing ( parroting ) unceasingly: Hello! Hello! Hello! ... Suppose now that your Parrot is a Kamikaze Robot: it blabs so much that it will explode itself after some time. We'll attach a Time Bomb to the parroting robot, so that it will stop blabbing after a while: object \"Time Bomb\" { state \"main\" { if ( timeout ( 15 )) // explode after 15 seconds state = \"explode\" ; } state \"explode\" { Console . print ( \"BOOOM!\" ); parent . destroy (); // destroy the parent object } } object \"Parrot\" is \"entity\" { blabber = spawn ( \"Blabber\" ); bomb = spawn ( \"Time Bomb\" ); state \"main\" { } } Now, here's the output: Hello! Hello! Hello! Hello! Hello! Hello! Hello! BOOOM! In this example, Parrot is an entity and Blabber and Time Bomb are its components. Once the entity is destroyed, its components (its children) are also destroyed automatically.","title":"Introduction"},{"location":"tutorials/components/#design-considerations","text":"In some implementations of ECS, entities are implemented as integers and components consist of raw data only. The game logic is executed by the System layer, which iterates throughout all entities continuously and executes the logic according to the components attached to them. In SurgeScript, components execute their own code and can be attached to entities simply by spawning them as children. Still, you can use the former approach if you wish to do so.","title":"Design considerations"},{"location":"tutorials/components/#composition-over-inheritance","text":"SurgeScript does not explicitly support inheritance, a feature found in other object-oriented languages. The usage of components is encouraged instead. SurgeScript favors composition over inheritance, allowing for greater flexibility when defining in-game objects.","title":"Composition over inheritance"},{"location":"tutorials/conditionals/","text":"Conditionals Introduction Conditionals are if ... then ... statements. If a certain condition evaluates to true , execute a block of code. If not, don't execute it. if ( condition ) { // this will be executed only if // the condition is true } Alternatively, we may include an else statement followed by a block of code that will only be executed if the condition is not true: if ( condition ) { // this will be executed only if // the condition is true } else { // this will be executed only if // the condition is false } Example The following example will print underaged if variable age is less than 18, or adult otherwise: object \"Application\" { age = 23 ; state \"main\" { if ( age < 18 ) { // variable age is less than 18 Console . print ( \"underaged\" ); } else { // variable age is not less than 18 Console . print ( \"adult\" ); } } } Inline conditionals Just like other languages with C-based syntax, the expression condition ? true_value : false_value evaluates to true_value if condition is true and to false_value if condition is false . For example, the script below will print underaged if variable age is less than 18, or adult otherwise: object \"Application\" { age = 23 ; message = age < 18 ? \"underaged\" : \"adult\" ; state \"main\" { Console . print ( message ); } }","title":"Conditionals"},{"location":"tutorials/conditionals/#conditionals","text":"","title":"Conditionals"},{"location":"tutorials/conditionals/#introduction","text":"Conditionals are if ... then ... statements. If a certain condition evaluates to true , execute a block of code. If not, don't execute it. if ( condition ) { // this will be executed only if // the condition is true } Alternatively, we may include an else statement followed by a block of code that will only be executed if the condition is not true: if ( condition ) { // this will be executed only if // the condition is true } else { // this will be executed only if // the condition is false }","title":"Introduction"},{"location":"tutorials/conditionals/#example","text":"The following example will print underaged if variable age is less than 18, or adult otherwise: object \"Application\" { age = 23 ; state \"main\" { if ( age < 18 ) { // variable age is less than 18 Console . print ( \"underaged\" ); } else { // variable age is not less than 18 Console . print ( \"adult\" ); } } }","title":"Example"},{"location":"tutorials/conditionals/#inline-conditionals","text":"Just like other languages with C-based syntax, the expression condition ? true_value : false_value evaluates to true_value if condition is true and to false_value if condition is false . For example, the script below will print underaged if variable age is less than 18, or adult otherwise: object \"Application\" { age = 23 ; message = age < 18 ? \"underaged\" : \"adult\" ; state \"main\" { Console . print ( message ); } }","title":"Inline conditionals"},{"location":"tutorials/expressions/","text":"Expressions SurgeScript supports many kinds of expressions. Expressions may involve strings, numbers or booleans. Let's study each case: Constants Constants are types of expressions. They may be numbers, strings, booleans... You may attribute constant values to variables using the assignment operator ( = ): // strings name = \"Surge\" ; // variable name receives string \"Surge\" message = \"Surge's home\" ; otherMessage = ' Single - quoted strings are also allowed ' ; // numbers weight = 35 ; speed = 42.2 ; // booleans like = true ; crazy = false ; // null next = null ; Arithmetic operators SurgeScript can perform basic arithmetic. The operators are as follows: Operator Meaning + Addition - Subtraction * Multiplication / Division % Remainder The multiplication, division and remainder operators have precedence over the addition and the subtraction operators. Examples: two = 1 + 1 ; ten = 5 * 2 ; eleven = 5 * 2 + 1 ; four = two * two ; fifteen = eleven + four ; three = fifteen / 5 ; positive = + 5 ; negative = - 1 ; zero = 15 - 10 - 5 ; one = 15 - ( 10 + 4 ); twelve = ( 2 + 2 ) * 3 ; prime = -(- 15 + 8 ); seven = 5 + 5 % 3 ; negativeTwo = - 5 % 3 ; Comparison operators Comparison operators compare two operands. Operator Meaning == Equality operator != Inequality operator < Less than <= Less or equal > Greater than >= Greater or equal === Strong equality !== Strong inequality Examples: x = 1 ; y = ( x == 1 ); // y is true z = ( x != 1 ); // z is false w = x > 1 ; // w is false t = x >= 1 ; // t is true Pay attention! Notice that the equality operator, used for comparing expressions for equality, is == . Pay attention! Don't confuse the equality operator ( == ) with the assignment operator ( = ). The expression (x = 1) always evaluates to 1, whereas (x == 1) is true only if x equals 1. Strong equality Unlike their counterparts, strong equality/inequality operators compare not only the content of the operands, but also their type. While \"1\" == 1 evalutes to true , \"1\" === 1 does not. Logical operators Logical operators involve booleans ( true or false values). While the not operator requires only one operand, operators and and or require two. Operator Meaning && and || or ! not The table below summarizes the basic logical expressions: Expression Result a && b true only if both a and b are true a || b true if a is true or b is true !a true if a is false, false if a is true Notice that not has higher precedence than the other two operators. Examples: x = 5 < 2 ; // evaluates to false y = ! x ; // evaluates to true z = 18 < 35 || x ; // evaluates to true w = ( z && x ) || true ; // evaluates to true t = ! x && x ; // evaluates to false Short-circuit evaluation SurgeScript performs short-circuit evaluation in and and or operations. This means that the second operator is not evaluated if the first alone is sufficient to determine the value of the operation. Example: in the expression a || b , expression b is not evaluated if a is evaluated to true . Similarly, in a && b , expression b is not evaluated if a is evaluated to false . Textual expressions You may concatenate strings with the + operator. Example: message = \"Surge\" + \" rocks!\" ; // evaluates to \"Surge rocks!\" Other data types, such as numbers and booleans, may also be implicitly converted to strings when using this feature. Example: group = \"Jackson \" + 5 ; // evaluates to \"Jackson 5\" Assignment operators The attribution operator ( = ) may be used to attribute data to variables. However, there's more to it. The expression variable = \"data\" is itself evaluated to string \"data\" . Likewise, the expression variable = variable + 5 is evaluated to the new value of the variable and may be shortened to variable += 5 . Let's see what kind of assignment expressions we have: Expression Translates to Meaning x = value x = value Assigns value to x x += value x = x + value Adds value to x x -= value x = x - value Subtracts value from x x *= value x = x * value Multiplies x by value x /= value x = x / value Divides x by value x %= value x = x % value Sets x to the remainder of x / value Example: language = \"Surge\" ; language += \"Script\" ; // language now evaluates to \"SurgeScript\" number = 5 ; number += 2 ; // number now evaluates to 7 Increment and decrement Increment and decrement operators should be used only on numeric variables. Expression Meaning x++ Increments x by 1 and returns the old value of x x-- Decrements x by 1 and returns the old value of x ++x Increments x by 1 and returns the new value of x --x Decrements x by 1 and returns the new value of x Example: x = 1 ; // x is 1 y = x ++; // y is 1 z = ++ x ; // z is 3 w = -- x ; // w is 2 t = -- x ; // t is 1 Console . print ( x ); // prints 1 Chained expressions You may chain assignment operations: x = y = z = 1 ; Commas The comma operator takes two operands. It first evaluates the first operand and then discards the result. Next, it evaluates the second operand and then returns this result. The comma is the operator with the lowest precedence. c = ( 1 , 2 ); // Results in c = 2 a = 1 , b = 2 , c = 3 ; // Results in a = 1, b = 2 and c = 3 d = ( c ++, a ); // Results in c = 4, d = 1 e = (++ a , f = 2 , 3 ); // Results in a = 2, e = 3, f = 2 Other expressions this The keyword this represents the object in which it appears. Example: this . destroy (); // destroys this object typeof The expression typeof(expr) (or simply typeof expr ), is evaluated to a string corresponding to the type of expr . The possible types are: number , string , boolean , object or null . Example: t = typeof 5 ; // t will hold the string \"number\" timeout The expression timeout(seconds) is a handy feature of SurgeScript. It is evaluated to true if the object has been on the same state for the specified amount of time or more. It can only be used inside states. Example: object \"Application\" { state \"main\" { if ( timeout ( 2.0 )) { Console . print ( \"2 seconds have passed\" ); state = \"done\" ; } } state \"done\" { } }","title":"Expressions"},{"location":"tutorials/expressions/#expressions","text":"SurgeScript supports many kinds of expressions. Expressions may involve strings, numbers or booleans. Let's study each case:","title":"Expressions"},{"location":"tutorials/expressions/#constants","text":"Constants are types of expressions. They may be numbers, strings, booleans... You may attribute constant values to variables using the assignment operator ( = ): // strings name = \"Surge\" ; // variable name receives string \"Surge\" message = \"Surge's home\" ; otherMessage = ' Single - quoted strings are also allowed ' ; // numbers weight = 35 ; speed = 42.2 ; // booleans like = true ; crazy = false ; // null next = null ;","title":"Constants"},{"location":"tutorials/expressions/#arithmetic-operators","text":"SurgeScript can perform basic arithmetic. The operators are as follows: Operator Meaning + Addition - Subtraction * Multiplication / Division % Remainder The multiplication, division and remainder operators have precedence over the addition and the subtraction operators. Examples: two = 1 + 1 ; ten = 5 * 2 ; eleven = 5 * 2 + 1 ; four = two * two ; fifteen = eleven + four ; three = fifteen / 5 ; positive = + 5 ; negative = - 1 ; zero = 15 - 10 - 5 ; one = 15 - ( 10 + 4 ); twelve = ( 2 + 2 ) * 3 ; prime = -(- 15 + 8 ); seven = 5 + 5 % 3 ; negativeTwo = - 5 % 3 ;","title":"Arithmetic operators"},{"location":"tutorials/expressions/#comparison-operators","text":"Comparison operators compare two operands. Operator Meaning == Equality operator != Inequality operator < Less than <= Less or equal > Greater than >= Greater or equal === Strong equality !== Strong inequality Examples: x = 1 ; y = ( x == 1 ); // y is true z = ( x != 1 ); // z is false w = x > 1 ; // w is false t = x >= 1 ; // t is true Pay attention! Notice that the equality operator, used for comparing expressions for equality, is == . Pay attention! Don't confuse the equality operator ( == ) with the assignment operator ( = ). The expression (x = 1) always evaluates to 1, whereas (x == 1) is true only if x equals 1. Strong equality Unlike their counterparts, strong equality/inequality operators compare not only the content of the operands, but also their type. While \"1\" == 1 evalutes to true , \"1\" === 1 does not.","title":"Comparison operators"},{"location":"tutorials/expressions/#logical-operators","text":"Logical operators involve booleans ( true or false values). While the not operator requires only one operand, operators and and or require two. Operator Meaning && and || or ! not The table below summarizes the basic logical expressions: Expression Result a && b true only if both a and b are true a || b true if a is true or b is true !a true if a is false, false if a is true Notice that not has higher precedence than the other two operators. Examples: x = 5 < 2 ; // evaluates to false y = ! x ; // evaluates to true z = 18 < 35 || x ; // evaluates to true w = ( z && x ) || true ; // evaluates to true t = ! x && x ; // evaluates to false Short-circuit evaluation SurgeScript performs short-circuit evaluation in and and or operations. This means that the second operator is not evaluated if the first alone is sufficient to determine the value of the operation. Example: in the expression a || b , expression b is not evaluated if a is evaluated to true . Similarly, in a && b , expression b is not evaluated if a is evaluated to false .","title":"Logical operators"},{"location":"tutorials/expressions/#textual-expressions","text":"You may concatenate strings with the + operator. Example: message = \"Surge\" + \" rocks!\" ; // evaluates to \"Surge rocks!\" Other data types, such as numbers and booleans, may also be implicitly converted to strings when using this feature. Example: group = \"Jackson \" + 5 ; // evaluates to \"Jackson 5\"","title":"Textual expressions"},{"location":"tutorials/expressions/#assignment-operators","text":"The attribution operator ( = ) may be used to attribute data to variables. However, there's more to it. The expression variable = \"data\" is itself evaluated to string \"data\" . Likewise, the expression variable = variable + 5 is evaluated to the new value of the variable and may be shortened to variable += 5 . Let's see what kind of assignment expressions we have: Expression Translates to Meaning x = value x = value Assigns value to x x += value x = x + value Adds value to x x -= value x = x - value Subtracts value from x x *= value x = x * value Multiplies x by value x /= value x = x / value Divides x by value x %= value x = x % value Sets x to the remainder of x / value Example: language = \"Surge\" ; language += \"Script\" ; // language now evaluates to \"SurgeScript\" number = 5 ; number += 2 ; // number now evaluates to 7","title":"Assignment operators"},{"location":"tutorials/expressions/#increment-and-decrement","text":"Increment and decrement operators should be used only on numeric variables. Expression Meaning x++ Increments x by 1 and returns the old value of x x-- Decrements x by 1 and returns the old value of x ++x Increments x by 1 and returns the new value of x --x Decrements x by 1 and returns the new value of x Example: x = 1 ; // x is 1 y = x ++; // y is 1 z = ++ x ; // z is 3 w = -- x ; // w is 2 t = -- x ; // t is 1 Console . print ( x ); // prints 1","title":"Increment and decrement"},{"location":"tutorials/expressions/#chained-expressions","text":"You may chain assignment operations: x = y = z = 1 ;","title":"Chained expressions"},{"location":"tutorials/expressions/#commas","text":"The comma operator takes two operands. It first evaluates the first operand and then discards the result. Next, it evaluates the second operand and then returns this result. The comma is the operator with the lowest precedence. c = ( 1 , 2 ); // Results in c = 2 a = 1 , b = 2 , c = 3 ; // Results in a = 1, b = 2 and c = 3 d = ( c ++, a ); // Results in c = 4, d = 1 e = (++ a , f = 2 , 3 ); // Results in a = 2, e = 3, f = 2","title":"Commas"},{"location":"tutorials/expressions/#other-expressions","text":"","title":"Other expressions"},{"location":"tutorials/expressions/#this","text":"The keyword this represents the object in which it appears. Example: this . destroy (); // destroys this object","title":"this"},{"location":"tutorials/expressions/#typeof","text":"The expression typeof(expr) (or simply typeof expr ), is evaluated to a string corresponding to the type of expr . The possible types are: number , string , boolean , object or null . Example: t = typeof 5 ; // t will hold the string \"number\"","title":"typeof"},{"location":"tutorials/expressions/#timeout","text":"The expression timeout(seconds) is a handy feature of SurgeScript. It is evaluated to true if the object has been on the same state for the specified amount of time or more. It can only be used inside states. Example: object \"Application\" { state \"main\" { if ( timeout ( 2.0 )) { Console . print ( \"2 seconds have passed\" ); state = \"done\" ; } } state \"done\" { } }","title":"timeout"},{"location":"tutorials/functions/","text":"Functions Introduction Functions are blocks of code that you can reuse throughout your program. They may receive input parameters and they always output something. The syntax is as follows: fun function_name ( param_1 , param_2 , param_3 , ..., param_n ) { // block of code // to be executed } Functions may be associated to objects. Any function associated to an object may be used (called) by the object itself or by other objects. This means that functions are public (they are visible to the outside world). Note: functions must be defined after the states. Return statement Use the return statement to stop executing the function and to return some value to the caller. Example: // This function will return the double of input parameter x fun double ( x ) { return 2 * x ; Console . print ( \"This line will never be executed.\" ); } If no value is specified after the return keyword, the function will be stopped and its return value will be null . Additionally, if no return statement is found, then the return value will also be null . Note : an object state may also contain one or more return statements to stop the execution of its code. However, return values must not be specified in that context, since states do not return values. Simple example In the example below, we have an object called Calculator with two functions: greet() and sum() . greet() takes no input parameters and just greets the user. On the other hand, sum() takes two input parameters, a and b , and returns the sum a + b : object \"Calculator\" { fun greet () { Console . print ( \"Hello! I am a Calculator!\" ); } fun sum ( a , b ) { return a + b ; } } In function sum() , variables a and b hold the input data and are only visible inside the function. Now, let's create a program that uses this Calculator . Remember that the functions defined above can be called by any object, including Application : object \"Application\" { calculator = spawn ( \"Calculator\" ); state \"main\" { // greet the user calculator . greet (); // do some computation result = calculator . sum ( 5 , 7 ); Console . print ( result ); // we're done! Application . exit (); } } The output of the above program is: Hello! I am a Calculator! 12 Notice that the Application does not need to know how the functions of the Calculator are implemented. It just needs to know what they do. This means that you may change the implementation of the Calculator without changing the Application , and the end-result will stay the same. Recursive functions In SurgeScript, a function is said to be recursive when it calls itself within its code. Recursion can be useful in many ways; namely, when you define a problem in terms of itself. In mathematics, the factorial of a non-negative integer number n , denoted as n! , is such an example: n! = { n * (n-1)! if n > 1 { 1 otherwise One interesting example of recursion that arises in computer science is called the binary search algorithm. Given a sorted Array , the binary search finds the position of a target value without having to inspect the whole collection. In the example below, bsearch() is a recursive function: object \"Binary Search\" { // Given an array sorted in ascending order, find() // finds the position of the target value in the array. // It returns its index, or -1 if the target is not found. fun find ( array , value ) { return bsearch ( array , value , 0 , array . length - 1 ); } // Performs a binary search in array[start..end] fun bsearch ( array , value , start , end ) { // get the middle point mid = start + Math . floor (( end - start ) / 2 ); // compare the middle point to the target value if ( start > end ) return - 1 ; // target not found else if ( value == array [ mid ]) return mid ; // found the target value else if ( value < array [ mid ]) return bsearch ( array , value , start , mid - 1 ); else return bsearch ( array , value , mid + 1 , end ); } } Recursive functions must have at least one base case. A base case is a scenario that does not need recursion to solve the problem. In the factorial example, the base case is n <= 1 (the factorial is 1). In the binary search example, the base case is start > end , meaning that the array is empty and the target value cannot be found, or value == array[mid] , meaning that the target value has been found at mid . How to understand recursion A sage once said: \"to understand recursion, you must first understand recursion\". Constructors and destructors In SurgeScript, constructors and destructors are special functions that are called whenever objects are created and destroyed, respectively. It's not mandatory to define them, but it may be useful to do so (you may want to set up things in your constructors, for example). Neither may receive any arguments (to set up objects with parameters, take a look at chaining ). Let's take our Calculator again. In the following example, constructor() is called automatically whenever a Calculator object is created. Likewise, destructor() is called automatically when the object is destroyed. object \"Calculator\" { fun constructor () { Console . print ( \"Creating a Calculator...\" ); } fun destructor () { Console . print ( \"Destroying a Calculator...\" ); } fun greet () { Console . print ( \"Hello! I am a Calculator!\" ); } fun sum ( a , b ) { return a + b ; } } Now, if we run the Application of the previous section without any modification, the output of the program will be: Creating a Calculator... Hello! I am a Calculator! 12 Destroying a Calculator... Note that, for any object, its constructor() runs before its main state.","title":"Functions"},{"location":"tutorials/functions/#functions","text":"","title":"Functions"},{"location":"tutorials/functions/#introduction","text":"Functions are blocks of code that you can reuse throughout your program. They may receive input parameters and they always output something. The syntax is as follows: fun function_name ( param_1 , param_2 , param_3 , ..., param_n ) { // block of code // to be executed } Functions may be associated to objects. Any function associated to an object may be used (called) by the object itself or by other objects. This means that functions are public (they are visible to the outside world). Note: functions must be defined after the states.","title":"Introduction"},{"location":"tutorials/functions/#return-statement","text":"Use the return statement to stop executing the function and to return some value to the caller. Example: // This function will return the double of input parameter x fun double ( x ) { return 2 * x ; Console . print ( \"This line will never be executed.\" ); } If no value is specified after the return keyword, the function will be stopped and its return value will be null . Additionally, if no return statement is found, then the return value will also be null . Note : an object state may also contain one or more return statements to stop the execution of its code. However, return values must not be specified in that context, since states do not return values.","title":"Return statement"},{"location":"tutorials/functions/#simple-example","text":"In the example below, we have an object called Calculator with two functions: greet() and sum() . greet() takes no input parameters and just greets the user. On the other hand, sum() takes two input parameters, a and b , and returns the sum a + b : object \"Calculator\" { fun greet () { Console . print ( \"Hello! I am a Calculator!\" ); } fun sum ( a , b ) { return a + b ; } } In function sum() , variables a and b hold the input data and are only visible inside the function. Now, let's create a program that uses this Calculator . Remember that the functions defined above can be called by any object, including Application : object \"Application\" { calculator = spawn ( \"Calculator\" ); state \"main\" { // greet the user calculator . greet (); // do some computation result = calculator . sum ( 5 , 7 ); Console . print ( result ); // we're done! Application . exit (); } } The output of the above program is: Hello! I am a Calculator! 12 Notice that the Application does not need to know how the functions of the Calculator are implemented. It just needs to know what they do. This means that you may change the implementation of the Calculator without changing the Application , and the end-result will stay the same.","title":"Simple example"},{"location":"tutorials/functions/#recursive-functions","text":"In SurgeScript, a function is said to be recursive when it calls itself within its code. Recursion can be useful in many ways; namely, when you define a problem in terms of itself. In mathematics, the factorial of a non-negative integer number n , denoted as n! , is such an example: n! = { n * (n-1)! if n > 1 { 1 otherwise One interesting example of recursion that arises in computer science is called the binary search algorithm. Given a sorted Array , the binary search finds the position of a target value without having to inspect the whole collection. In the example below, bsearch() is a recursive function: object \"Binary Search\" { // Given an array sorted in ascending order, find() // finds the position of the target value in the array. // It returns its index, or -1 if the target is not found. fun find ( array , value ) { return bsearch ( array , value , 0 , array . length - 1 ); } // Performs a binary search in array[start..end] fun bsearch ( array , value , start , end ) { // get the middle point mid = start + Math . floor (( end - start ) / 2 ); // compare the middle point to the target value if ( start > end ) return - 1 ; // target not found else if ( value == array [ mid ]) return mid ; // found the target value else if ( value < array [ mid ]) return bsearch ( array , value , start , mid - 1 ); else return bsearch ( array , value , mid + 1 , end ); } } Recursive functions must have at least one base case. A base case is a scenario that does not need recursion to solve the problem. In the factorial example, the base case is n <= 1 (the factorial is 1). In the binary search example, the base case is start > end , meaning that the array is empty and the target value cannot be found, or value == array[mid] , meaning that the target value has been found at mid . How to understand recursion A sage once said: \"to understand recursion, you must first understand recursion\".","title":"Recursive functions"},{"location":"tutorials/functions/#constructors-and-destructors","text":"In SurgeScript, constructors and destructors are special functions that are called whenever objects are created and destroyed, respectively. It's not mandatory to define them, but it may be useful to do so (you may want to set up things in your constructors, for example). Neither may receive any arguments (to set up objects with parameters, take a look at chaining ). Let's take our Calculator again. In the following example, constructor() is called automatically whenever a Calculator object is created. Likewise, destructor() is called automatically when the object is destroyed. object \"Calculator\" { fun constructor () { Console . print ( \"Creating a Calculator...\" ); } fun destructor () { Console . print ( \"Destroying a Calculator...\" ); } fun greet () { Console . print ( \"Hello! I am a Calculator!\" ); } fun sum ( a , b ) { return a + b ; } } Now, if we run the Application of the previous section without any modification, the output of the program will be: Creating a Calculator... Hello! I am a Calculator! 12 Destroying a Calculator... Note that, for any object, its constructor() runs before its main state.","title":"Constructors and destructors"},{"location":"tutorials/hello/","text":"Hello, World! SurgeScript creates automatically an object called Application . That object is defined by the user. Let's see how we can use that to make a simple program: object \"Application\" { state \"main\" { Console . print ( \"Hello, world!\" ); Application . exit (); } } In SurgeScript, each object defines a state machine (more on that later). The initial state is called main . In the code just presented, we display a Hello, world! message and then exit the app. Now let's test your scripts .","title":"Hello, World!"},{"location":"tutorials/hello/#hello-world","text":"SurgeScript creates automatically an object called Application . That object is defined by the user. Let's see how we can use that to make a simple program: object \"Application\" { state \"main\" { Console . print ( \"Hello, world!\" ); Application . exit (); } } In SurgeScript, each object defines a state machine (more on that later). The initial state is called main . In the code just presented, we display a Hello, world! message and then exit the app. Now let's test your scripts .","title":"Hello, World!"},{"location":"tutorials/loops/","text":"Loops While loops In a while loop, you execute a certain block of code while a condition is true. The syntax is as follows: while ( condition ) { // block of code // to be executed } The example below counts from 1 to 10: i = 1 ; while ( i <= 10 ) { Console . print ( i ); i = i + 1 ; } The following example prints nothing. The while loop is skipped because the condition is initially false: i = 20 ; while ( i <= 10 ) { // this condition is false Console . print ( i ); i = i + 1 ; } Do-while loops Do-while loops are similar to while loops, except that the block of code is executed at least once, unconditionally. It is repeated while a condition is true. Syntax: do { // block of code // to be executed } while ( condition ); The example below counts from 1 to 10: i = 1 ; do { Console . print ( i ); i = i + 1 ; } while ( i <= 10 ); The following example prints the number 20. Since the condition is false, the block of code is executed only once: i = 20 ; do { Console . print ( i ); i = i + 1 ; } while ( i <= 10 ); // this condition is false Note: do-while loops are available since SurgeScript 0.6.0. For loops A for loop is a more controlled repetition structure compared to a while loop. For loops support an initialization command, a condition and an increment command. The syntax is as follows: for ( initialization ; condition ; increment ) { // block of code // to be executed } The for loop above is equivalent to: initialization ; while ( condition ) { // block of code // to be executed increment ; } The example below counts from 1 to 10: for ( i = 1 ; i <= 10 ; i ++) { Console . print ( i ); } Foreach Foreach loops are used to iterate throughout iterable collections (such as Arrays and Dictionaries ). Basically: for each element x in the iterable collection, do something with x . The syntax is as follows: foreach ( element in collection ) { // block of code // to be executed } The example below counts from 1 to 10: collection = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]; foreach ( x in collection ) { Console . print ( x ); } The example below iterates over a Dictionary : dictionary = { \"a\" : 1 , \"b\" : 2 , \"c\" : 3 }; foreach ( entry in dictionary ) { Console . print ( entry . key ); Console . print ( entry . value ); } Implementing your own iterable collections The foreach loop can be used with any iterable collections, not only Arrays and Dictionaries . You may even implement your own!","title":"Loops"},{"location":"tutorials/loops/#loops","text":"","title":"Loops"},{"location":"tutorials/loops/#while-loops","text":"In a while loop, you execute a certain block of code while a condition is true. The syntax is as follows: while ( condition ) { // block of code // to be executed } The example below counts from 1 to 10: i = 1 ; while ( i <= 10 ) { Console . print ( i ); i = i + 1 ; } The following example prints nothing. The while loop is skipped because the condition is initially false: i = 20 ; while ( i <= 10 ) { // this condition is false Console . print ( i ); i = i + 1 ; }","title":"While loops"},{"location":"tutorials/loops/#do-while-loops","text":"Do-while loops are similar to while loops, except that the block of code is executed at least once, unconditionally. It is repeated while a condition is true. Syntax: do { // block of code // to be executed } while ( condition ); The example below counts from 1 to 10: i = 1 ; do { Console . print ( i ); i = i + 1 ; } while ( i <= 10 ); The following example prints the number 20. Since the condition is false, the block of code is executed only once: i = 20 ; do { Console . print ( i ); i = i + 1 ; } while ( i <= 10 ); // this condition is false Note: do-while loops are available since SurgeScript 0.6.0.","title":"Do-while loops"},{"location":"tutorials/loops/#for-loops","text":"A for loop is a more controlled repetition structure compared to a while loop. For loops support an initialization command, a condition and an increment command. The syntax is as follows: for ( initialization ; condition ; increment ) { // block of code // to be executed } The for loop above is equivalent to: initialization ; while ( condition ) { // block of code // to be executed increment ; } The example below counts from 1 to 10: for ( i = 1 ; i <= 10 ; i ++) { Console . print ( i ); }","title":"For loops"},{"location":"tutorials/loops/#foreach","text":"Foreach loops are used to iterate throughout iterable collections (such as Arrays and Dictionaries ). Basically: for each element x in the iterable collection, do something with x . The syntax is as follows: foreach ( element in collection ) { // block of code // to be executed } The example below counts from 1 to 10: collection = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]; foreach ( x in collection ) { Console . print ( x ); } The example below iterates over a Dictionary : dictionary = { \"a\" : 1 , \"b\" : 2 , \"c\" : 3 }; foreach ( entry in dictionary ) { Console . print ( entry . key ); Console . print ( entry . value ); } Implementing your own iterable collections The foreach loop can be used with any iterable collections, not only Arrays and Dictionaries . You may even implement your own!","title":"Foreach"},{"location":"tutorials/object_tree/","text":"Object tree Introduction In SurgeScript, objects have a hierarchical relationship. Suppose that object P spawns (or instantiates ) object C. We say that object P is the parent of C. Similarly, object C is a child of P. An object may spawn many children. However, all objects have only one parent. This relationship between objects forms a hierarchy (a tree). The Figure below shows an example: In this example, Level is the parent of GameItem1 and GameItem2. Components A and B are children of GameItem1, but not of GameItem2. Level has two children and GameItem2 has zero. Finally, GameItem1, GameItem2, Component A and Component B are all descendants of Level. In SurgeScript, the root of the hierarchy is a predefined object called System . Its parent is itself. All other objects are descendants of System . Spawning objects You can use spawn() to instantiate an object. Example: object \"Parent\" { child = spawn ( \"Child\" ); state \"main\" { } } object \"Child\" { state \"main\" { } } Function spawn() may be invoked on objects other than the caller. In this case, the caller won't be the parent of the newly created object: object \"Parent\" { child = spawn ( \"Child\" ); grandChild = child . spawn ( \"Child\" ); state \"main\" { } } Automatic Garbage Collection When you spawn an object, make sure you store a reference to it somewhere. If an object cannot be reached from the root (no reachable object has any references to it), it will be automatically destroyed by SurgeScript's built-in garbage collector. Destroying objects Objects can be destroyed manually by calling destroy() . Whenever an object is destroyed, its children are destroyed as well. object \"Foo\" { state \"main\" { Console . print ( \"This object does nothing.\" ); destroy (); } } Traversing the hierarchy Relevant data about the object hierarchy can be obtained using the following properties and functions (find out more about them at the Object reference ): Function / property Description obj.parent The parent object obj.child(name) Gets a child object named name obj.findObject(name) Finds a descendant named name obj.__childCount Number of immediate children Example: object \"Parent\" { child = spawn ( \"Child\" ); otherChild = spawn ( \"Child\" ); state \"main\" { Console . print ( \"This object has \" + this . __childCount + \" children.\" ); destroy (); } } The output is as follows: This object has 2 children.","title":"Object tree"},{"location":"tutorials/object_tree/#object-tree","text":"","title":"Object tree"},{"location":"tutorials/object_tree/#introduction","text":"In SurgeScript, objects have a hierarchical relationship. Suppose that object P spawns (or instantiates ) object C. We say that object P is the parent of C. Similarly, object C is a child of P. An object may spawn many children. However, all objects have only one parent. This relationship between objects forms a hierarchy (a tree). The Figure below shows an example: In this example, Level is the parent of GameItem1 and GameItem2. Components A and B are children of GameItem1, but not of GameItem2. Level has two children and GameItem2 has zero. Finally, GameItem1, GameItem2, Component A and Component B are all descendants of Level. In SurgeScript, the root of the hierarchy is a predefined object called System . Its parent is itself. All other objects are descendants of System .","title":"Introduction"},{"location":"tutorials/object_tree/#spawning-objects","text":"You can use spawn() to instantiate an object. Example: object \"Parent\" { child = spawn ( \"Child\" ); state \"main\" { } } object \"Child\" { state \"main\" { } } Function spawn() may be invoked on objects other than the caller. In this case, the caller won't be the parent of the newly created object: object \"Parent\" { child = spawn ( \"Child\" ); grandChild = child . spawn ( \"Child\" ); state \"main\" { } } Automatic Garbage Collection When you spawn an object, make sure you store a reference to it somewhere. If an object cannot be reached from the root (no reachable object has any references to it), it will be automatically destroyed by SurgeScript's built-in garbage collector.","title":"Spawning objects"},{"location":"tutorials/object_tree/#destroying-objects","text":"Objects can be destroyed manually by calling destroy() . Whenever an object is destroyed, its children are destroyed as well. object \"Foo\" { state \"main\" { Console . print ( \"This object does nothing.\" ); destroy (); } }","title":"Destroying objects"},{"location":"tutorials/object_tree/#traversing-the-hierarchy","text":"Relevant data about the object hierarchy can be obtained using the following properties and functions (find out more about them at the Object reference ): Function / property Description obj.parent The parent object obj.child(name) Gets a child object named name obj.findObject(name) Finds a descendant named name obj.__childCount Number of immediate children Example: object \"Parent\" { child = spawn ( \"Child\" ); otherChild = spawn ( \"Child\" ); state \"main\" { Console . print ( \"This object has \" + this . __childCount + \" children.\" ); destroy (); } } The output is as follows: This object has 2 children.","title":"Traversing the hierarchy"},{"location":"tutorials/objects/","text":"Introduction to objects Introduction In SurgeScript, objects are units of code and data. Each object defines a finite state machine, a mathematical construct used to describe the behavior of in-game objects. Did you know? Games implement what is called a game loop. In SurgeScript, the game loop is defined implicitly via state machines. State machines are one of the key features of SurgeScript. State machines A finite state machine is a mathematical abstraction composed of a finite number of states and by transitions between these states. Only one state can be active at any given time (we'll call it the active state ). There must be one initial state (i.e., the first one to be active). A transition is a change of the active state that is triggered when a certain condition is met. As a concrete example, suppose that you want to create a door in your game. You, the developer, may open or close the door at will. But what is a door? We have just given informal description of the problem. However, we need to transform it in something more rigorous. Example: A door is an object with two states (see the Figure below): Opened (initial state) Closed From the Opened state, only one transition is possible: Close. Once the Close transition is called, the door will go to the Closed state. Conversely, from the Closed state, only one transition is available: Open. When the Open transition is executed, the door will return to the Opened state. Objects in SurgeScript In SurgeScript, each object has a name. Objects may have any number of states you'd like. The initial state is always called main . The syntax is as follows: object \"name of the object\" { state \"state name\" { // code goes here } } The following code shows an example of a door that opens and closes (it keep changing states) every 2 seconds: object \"Cosmic Door\" { state \"main\" { // the object starts at the main state state = \"opened\" ; // go to the opened state } state \"opened\" { if ( timeout ( 2 )) // if we have been on the opened state for 2+ seconds state = \"closed\" ; // go to the closed state } state \"closed\" { if ( timeout ( 2 )) state = \"opened\" ; } } Notice how the code just shown defines states and transitions between these states. Each state contains its own code. Note: once a state is active, its code will be repeated at every frame of the application until the state changes or until the object is destroyed.","title":"Introduction to objects"},{"location":"tutorials/objects/#introduction-to-objects","text":"","title":"Introduction to objects"},{"location":"tutorials/objects/#introduction","text":"In SurgeScript, objects are units of code and data. Each object defines a finite state machine, a mathematical construct used to describe the behavior of in-game objects. Did you know? Games implement what is called a game loop. In SurgeScript, the game loop is defined implicitly via state machines. State machines are one of the key features of SurgeScript.","title":"Introduction"},{"location":"tutorials/objects/#state-machines","text":"A finite state machine is a mathematical abstraction composed of a finite number of states and by transitions between these states. Only one state can be active at any given time (we'll call it the active state ). There must be one initial state (i.e., the first one to be active). A transition is a change of the active state that is triggered when a certain condition is met. As a concrete example, suppose that you want to create a door in your game. You, the developer, may open or close the door at will. But what is a door? We have just given informal description of the problem. However, we need to transform it in something more rigorous. Example: A door is an object with two states (see the Figure below): Opened (initial state) Closed From the Opened state, only one transition is possible: Close. Once the Close transition is called, the door will go to the Closed state. Conversely, from the Closed state, only one transition is available: Open. When the Open transition is executed, the door will return to the Opened state.","title":"State machines"},{"location":"tutorials/objects/#objects-in-surgescript","text":"In SurgeScript, each object has a name. Objects may have any number of states you'd like. The initial state is always called main . The syntax is as follows: object \"name of the object\" { state \"state name\" { // code goes here } } The following code shows an example of a door that opens and closes (it keep changing states) every 2 seconds: object \"Cosmic Door\" { state \"main\" { // the object starts at the main state state = \"opened\" ; // go to the opened state } state \"opened\" { if ( timeout ( 2 )) // if we have been on the opened state for 2+ seconds state = \"closed\" ; // go to the closed state } state \"closed\" { if ( timeout ( 2 )) state = \"opened\" ; } } Notice how the code just shown defines states and transitions between these states. Each state contains its own code. Note: once a state is active, its code will be repeated at every frame of the application until the state changes or until the object is destroyed.","title":"Objects in SurgeScript"},{"location":"tutorials/packages/","text":"Packages Introduction Packages are objects that allow you to extend the functionalities of the language. Once declared, they can be imported anywhere in the code. They can also be easily shared with others, so everyone benefits. Available since: SurgeScript 0.5.2 Basic example Suppose you want to extend the language by adding new routines related to string manipulation. These routines will be used frequently throughout your project, and you'd like easy access to them. This makes it perfect for implementing them as a package. We'll define an object called StringUtils with a reverse() function that reverses a string. We make the object a package by annotating it with @Package . Take a look at the example below: // File: stringutils.ss @Package object \"StringUtils\" { fun reverse ( str ) { buf = \"\" ; for ( i = str . length - 1 ; i >= 0 ; i --) buf += str [ i ]; return buf ; } } When you annotate an object definition with @Package , SurgeScript will spawn an instance of such an object before spawning the Application . Additionally, the package object may be imported anywhere with the using keyword: // File: app.ss using StringUtils ; object \"Application\" { state \"main\" { str = StringUtils . reverse ( \"alucard\" ); Console . print ( str ); // will print \"dracula\" exit (); } } Note: it's recommended not to include any special characters in the name of your packages. Note: before SurgeScript 0.5.4, you would annotate the object with @Plugin instead. In the example above, Application and StringUtils are located in two separate files. If you want to test them using the SurgeScript command line utility, pass both files as parameters: surgescript package.ss app.ss Spawning order Although packages are spawned before the Application object, for the time being they are spawned in no particular order. You may not access a package from within the constructor of another package, as of now there is no dependency resolver implemented. Use the main state. Package example Packages may aggregate many code units with different functionalities. This lets you separate your code in coherent, logical units and also helps you to distribute it. Suppose that user Parrot , the owner of ParrotSoft , created SurgeScript utilities related to string manipulation, matrix math and complex numbers. He decided to share his code as a single package called ParrotSoft . Since he implemented getters for each of his utilities, his package provides easy access to all of them. Furthermore, he annotated his package with @Package (but not the individual utilities), so his package can be accessed anywhere. // File: parrotsoft.ss @Package object \"ParrotSoft\" { public readonly Matrices = spawn ( \"Parrot Matrices\" ); public readonly Complex = spawn ( \"Parrot Complex\" ); public readonly StringUtils = spawn ( \"Parrot StringUtils\" ); } A user of the ParrotSoft package may import Parrot 's utilities simply by importing the package. Individual utilities may also be imported. The code below shows an example: using ParrotSoft.Matrices.Matrix2 ; using ParrotSoft.Complex ; using ParrotSoft ; object \"Application\" { state \"main\" { identity = Matrix2 ([[ 1 , 0 ], [ 0 , 1 ]]); // 2x2 matrix z = Complex ( 2 , 3 ); // 2 + 3i neon = ParrotSoft . StringUtils . reverse ( \"noen\" ); exit (); } } In the example above, writing Complex is equivalent to writing ParrotSoft.Complex , since we imported this utility with using ParrotSoft.Complex . Notice that ParrotSoft implements a getter for Complex . Additionally, ParrotSoft has been annotated with @Package , but Complex has not . This means that the statement using Complex will not yield the expected result. Since Complex is a part of ParrotSoft , it can only be accessed from it. Finally, since we haven't imported StringUtils explicitly, we type ParrotSoft.StringUtils to access it. Pay attention! Combine related packages into one. Don't pollute the global namespace!","title":"Packages"},{"location":"tutorials/packages/#packages","text":"","title":"Packages"},{"location":"tutorials/packages/#introduction","text":"Packages are objects that allow you to extend the functionalities of the language. Once declared, they can be imported anywhere in the code. They can also be easily shared with others, so everyone benefits. Available since: SurgeScript 0.5.2","title":"Introduction"},{"location":"tutorials/packages/#basic-example","text":"Suppose you want to extend the language by adding new routines related to string manipulation. These routines will be used frequently throughout your project, and you'd like easy access to them. This makes it perfect for implementing them as a package. We'll define an object called StringUtils with a reverse() function that reverses a string. We make the object a package by annotating it with @Package . Take a look at the example below: // File: stringutils.ss @Package object \"StringUtils\" { fun reverse ( str ) { buf = \"\" ; for ( i = str . length - 1 ; i >= 0 ; i --) buf += str [ i ]; return buf ; } } When you annotate an object definition with @Package , SurgeScript will spawn an instance of such an object before spawning the Application . Additionally, the package object may be imported anywhere with the using keyword: // File: app.ss using StringUtils ; object \"Application\" { state \"main\" { str = StringUtils . reverse ( \"alucard\" ); Console . print ( str ); // will print \"dracula\" exit (); } } Note: it's recommended not to include any special characters in the name of your packages. Note: before SurgeScript 0.5.4, you would annotate the object with @Plugin instead. In the example above, Application and StringUtils are located in two separate files. If you want to test them using the SurgeScript command line utility, pass both files as parameters: surgescript package.ss app.ss Spawning order Although packages are spawned before the Application object, for the time being they are spawned in no particular order. You may not access a package from within the constructor of another package, as of now there is no dependency resolver implemented. Use the main state.","title":"Basic example"},{"location":"tutorials/packages/#package-example","text":"Packages may aggregate many code units with different functionalities. This lets you separate your code in coherent, logical units and also helps you to distribute it. Suppose that user Parrot , the owner of ParrotSoft , created SurgeScript utilities related to string manipulation, matrix math and complex numbers. He decided to share his code as a single package called ParrotSoft . Since he implemented getters for each of his utilities, his package provides easy access to all of them. Furthermore, he annotated his package with @Package (but not the individual utilities), so his package can be accessed anywhere. // File: parrotsoft.ss @Package object \"ParrotSoft\" { public readonly Matrices = spawn ( \"Parrot Matrices\" ); public readonly Complex = spawn ( \"Parrot Complex\" ); public readonly StringUtils = spawn ( \"Parrot StringUtils\" ); } A user of the ParrotSoft package may import Parrot 's utilities simply by importing the package. Individual utilities may also be imported. The code below shows an example: using ParrotSoft.Matrices.Matrix2 ; using ParrotSoft.Complex ; using ParrotSoft ; object \"Application\" { state \"main\" { identity = Matrix2 ([[ 1 , 0 ], [ 0 , 1 ]]); // 2x2 matrix z = Complex ( 2 , 3 ); // 2 + 3i neon = ParrotSoft . StringUtils . reverse ( \"noen\" ); exit (); } } In the example above, writing Complex is equivalent to writing ParrotSoft.Complex , since we imported this utility with using ParrotSoft.Complex . Notice that ParrotSoft implements a getter for Complex . Additionally, ParrotSoft has been annotated with @Package , but Complex has not . This means that the statement using Complex will not yield the expected result. Since Complex is a part of ParrotSoft , it can only be accessed from it. Finally, since we haven't imported StringUtils explicitly, we type ParrotSoft.StringUtils to access it. Pay attention! Combine related packages into one. Don't pollute the global namespace!","title":"Package example"},{"location":"tutorials/properties/","text":"Properties Introduction In SurgeScript, object-level variables are private. This means that these variables can only be accessed from the objects that defined them. However, SurgeScript features a syntactic sugar that allows objects to read and/or modify other objects' data in a way that looks like dealing with regular (public) variables. We'll call these \"variables\" properties . Defining properties Suppose you have an object called Animal with an object-level variable called sound and a function named speak() : object \"Animal\" { sound = \"meow!\" ; fun speak () { Console . print ( sound ); } } This object can only speak meow! Let's see: object \"Application\" { animal = spawn ( \"Animal\" ); state \"main\" { animal . speak (); } } Run this script and you'll see: meow! meow! meow! meow! ... What if an external object could modify the sound of the animal? Trying to access animal.sound externally will trigger an error, unless you add the public specifier to your variable: object \"Animal\" { public sound = \"meow!\" ; fun speak () { Console . print ( sound ); } } Now, external objects may access (read and write) the sound variable (or property ): object \"Application\" { animal = spawn ( \"Animal\" ); state \"main\" { animal . sound = \"woof!\" ; animal . speak (); } } Since SurgeScript 0.5.3, you may add the readonly modifier after the public specifier. Doing so disallows the modification of the property by external objects: object \"Animal\" { public readonly sound = \"meow!\" ; fun speak () { Console . print ( sound ); } } object \"Application\" { animal = spawn ( \"Animal\" ); state \"main\" { //animal.sound = \"woof!\"; // will trigger an error //Console.print(animal.sound); // this is allowed animal . speak (); } } Using getters and setters In reality, however, there are no public variables in SurgeScript. Behind the scenes, the language defines special functions called getters and setters that will perform the read/write logic for you. Rather than using public , you may want to define the getters and the setters yourself: object \"Animal\" { sound = \"meow!\" ; fun speak () { Console . print ( sound ); } fun set_sound ( value ) { sound = value ; } fun get_sound () { return sound ; } } This code is semantically the same as setting sound to be public ; this is just a bit longer. An advantage of defining getters and setters by yourself is that you control how the data passes through the objects. You may want to validate the data before changing the internal variables of the objects. Example: // lives must not be a negative number fun set_lives ( value ) { if ( value >= 0 ) lives = value ; else lives = 0 ; }","title":"Properties"},{"location":"tutorials/properties/#properties","text":"","title":"Properties"},{"location":"tutorials/properties/#introduction","text":"In SurgeScript, object-level variables are private. This means that these variables can only be accessed from the objects that defined them. However, SurgeScript features a syntactic sugar that allows objects to read and/or modify other objects' data in a way that looks like dealing with regular (public) variables. We'll call these \"variables\" properties .","title":"Introduction"},{"location":"tutorials/properties/#defining-properties","text":"Suppose you have an object called Animal with an object-level variable called sound and a function named speak() : object \"Animal\" { sound = \"meow!\" ; fun speak () { Console . print ( sound ); } } This object can only speak meow! Let's see: object \"Application\" { animal = spawn ( \"Animal\" ); state \"main\" { animal . speak (); } } Run this script and you'll see: meow! meow! meow! meow! ... What if an external object could modify the sound of the animal? Trying to access animal.sound externally will trigger an error, unless you add the public specifier to your variable: object \"Animal\" { public sound = \"meow!\" ; fun speak () { Console . print ( sound ); } } Now, external objects may access (read and write) the sound variable (or property ): object \"Application\" { animal = spawn ( \"Animal\" ); state \"main\" { animal . sound = \"woof!\" ; animal . speak (); } } Since SurgeScript 0.5.3, you may add the readonly modifier after the public specifier. Doing so disallows the modification of the property by external objects: object \"Animal\" { public readonly sound = \"meow!\" ; fun speak () { Console . print ( sound ); } } object \"Application\" { animal = spawn ( \"Animal\" ); state \"main\" { //animal.sound = \"woof!\"; // will trigger an error //Console.print(animal.sound); // this is allowed animal . speak (); } }","title":"Defining properties"},{"location":"tutorials/properties/#using-getters-and-setters","text":"In reality, however, there are no public variables in SurgeScript. Behind the scenes, the language defines special functions called getters and setters that will perform the read/write logic for you. Rather than using public , you may want to define the getters and the setters yourself: object \"Animal\" { sound = \"meow!\" ; fun speak () { Console . print ( sound ); } fun set_sound ( value ) { sound = value ; } fun get_sound () { return sound ; } } This code is semantically the same as setting sound to be public ; this is just a bit longer. An advantage of defining getters and setters by yourself is that you control how the data passes through the objects. You may want to validate the data before changing the internal variables of the objects. Example: // lives must not be a negative number fun set_lives ( value ) { if ( value >= 0 ) lives = value ; else lives = 0 ; }","title":"Using getters and setters"},{"location":"tutorials/tags/","text":"Tags You may tag objects with as many tags as you want. Tags are a way of attributing categories to objects. Syntax Tags should be placed right after the object name. Example: object \"Horse\" is \"animal\" , \"vehicle\" { state \"main\" { } } object \"Cat\" is \"animal\" { state \"main\" { } } object \"Car\" is \"vehicle\" { state \"main\" { } } Using tags You may check if an object has a particular tag with the hasTag() function (see the Object reference for more details): object \"Application\" { horse = spawn ( \"Horse\" ); cat = spawn ( \"Cat\" ); car = spawn ( \"Car\" ); state \"main\" { // Horse is both an animal and a vehicle Console . print ( horse . hasTag ( \"animal\" )); // true Console . print ( horse . hasTag ( \"vehicle\" )); // true // Cat is an animal, but not a vehicle Console . print ( cat . hasTag ( \"animal\" )); // true Console . print ( cat . hasTag ( \"vehicle\" )); // false // Car is a vehicle, but not an animal Console . print ( car . hasTag ( \"animal\" )); // false Console . print ( car . hasTag ( \"vehicle\" )); // true } }","title":"Tags"},{"location":"tutorials/tags/#tags","text":"You may tag objects with as many tags as you want. Tags are a way of attributing categories to objects.","title":"Tags"},{"location":"tutorials/tags/#syntax","text":"Tags should be placed right after the object name. Example: object \"Horse\" is \"animal\" , \"vehicle\" { state \"main\" { } } object \"Cat\" is \"animal\" { state \"main\" { } } object \"Car\" is \"vehicle\" { state \"main\" { } }","title":"Syntax"},{"location":"tutorials/tags/#using-tags","text":"You may check if an object has a particular tag with the hasTag() function (see the Object reference for more details): object \"Application\" { horse = spawn ( \"Horse\" ); cat = spawn ( \"Cat\" ); car = spawn ( \"Car\" ); state \"main\" { // Horse is both an animal and a vehicle Console . print ( horse . hasTag ( \"animal\" )); // true Console . print ( horse . hasTag ( \"vehicle\" )); // true // Cat is an animal, but not a vehicle Console . print ( cat . hasTag ( \"animal\" )); // true Console . print ( cat . hasTag ( \"vehicle\" )); // false // Car is a vehicle, but not an animal Console . print ( car . hasTag ( \"animal\" )); // false Console . print ( car . hasTag ( \"vehicle\" )); // true } }","title":"Using tags"},{"location":"tutorials/testing/","text":"Testing your scripts There are two main ways to test your scripts: using the Open Surge game engine; using the SurgeScript standalone runtime (i.e., the version without a game engine). Using Open Surge To test a script in Open Surge, place it on the scripts/ folder and start the engine. Your test script must include an object called Application . Make sure to remove the script after you're done with the testing. As an example, save the following script to scripts/hello.ss and start the engine: // hello.ss: test script // Please remove this file after you're done object \"Application\" { state \"main\" { Console . print ( \"Hello, world!\" ); state = \"done\" ; } state \"done\" { } } You should see the Hello, world! message as a result. Linux users: when using a system-wide installation, you may place your scripts on ~/.local/share/opensurge/scripts/ (i.e., $XDG_DATA_HOME/opensurge/scripts/ ). Ready to proceed? Let's go to Introduction to objects ! Using the standalone version If you've downloaded the standalone version of the language: First of all, save the following script to a file named hello.ss . For testing purposes, you may place the file on the same directory as the surgescript executable. // hello.ss: test script object \"Application\" { state \"main\" { Console . print ( \"Hello, world!\" ); Application . exit (); } } Then, open up a Terminal and type: cd /path/to/surgescript ./surgescript hello.ss If you're using Microsoft Windows, open up a Command Prompt and type: cd C:\\path\\to\\surgescript surgescript.exe hello.ss You should see the output of the script as a result: Hello, world! To begin our learning adventure, let's go to Introduction to objects .","title":"Testing your scripts"},{"location":"tutorials/testing/#testing-your-scripts","text":"There are two main ways to test your scripts: using the Open Surge game engine; using the SurgeScript standalone runtime (i.e., the version without a game engine).","title":"Testing your scripts"},{"location":"tutorials/testing/#using-open-surge","text":"To test a script in Open Surge, place it on the scripts/ folder and start the engine. Your test script must include an object called Application . Make sure to remove the script after you're done with the testing. As an example, save the following script to scripts/hello.ss and start the engine: // hello.ss: test script // Please remove this file after you're done object \"Application\" { state \"main\" { Console . print ( \"Hello, world!\" ); state = \"done\" ; } state \"done\" { } } You should see the Hello, world! message as a result. Linux users: when using a system-wide installation, you may place your scripts on ~/.local/share/opensurge/scripts/ (i.e., $XDG_DATA_HOME/opensurge/scripts/ ). Ready to proceed? Let's go to Introduction to objects !","title":"Using Open Surge"},{"location":"tutorials/testing/#using-the-standalone-version","text":"If you've downloaded the standalone version of the language: First of all, save the following script to a file named hello.ss . For testing purposes, you may place the file on the same directory as the surgescript executable. // hello.ss: test script object \"Application\" { state \"main\" { Console . print ( \"Hello, world!\" ); Application . exit (); } } Then, open up a Terminal and type: cd /path/to/surgescript ./surgescript hello.ss If you're using Microsoft Windows, open up a Command Prompt and type: cd C:\\path\\to\\surgescript surgescript.exe hello.ss You should see the output of the script as a result: Hello, world! To begin our learning adventure, let's go to Introduction to objects .","title":"Using the standalone version"},{"location":"tutorials/variables/","text":"Variables Introduction Variables are used to store data. SurgeScript features five basic types: number, string, boolean, null and object. Variables can also point to more complex data structures (such as arrays and dictionaries), but these are always objects. Types Basic types Type Description Examples Number A floating-point number 1 , 2 , -3 , 3.14159 String Some text \"Hello, world!\" , 'single-quoted' Boolean True or false true , false Object Reference to an object Application , this , [ ] Null An empty value null As an example, the script below features an object with 3 variables that may be accessed throughout the whole object: object \"Application\" { name = \"Surge the Rabbit\" ; age = 23 ; underage = false ; state \"main\" { Console . print ( name ); // Surge the Rabbit Console . print ( age ); // 23 } } Abstract types Arrays Arrays are collections of values that you may access using a zero-based index. Example: object \"Application\" { // The 'characters' array holds 3 strings characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; state \"main\" { // who are the characters? Console . print ( \"The characters are:\" ); Console . print ( characters [ 0 ]); // will print Surge Console . print ( characters [ 1 ]); // will print Neon Console . print ( characters [ 2 ]); // will print Charge // how many characters? Console . print ( \"Number of characters:\" ); Console . print ( characters . length ); // will print 3 } } Arrays have many interesting properties and operations that you can see in the Language Reference . Dictionaries Dictionaries are collections of key-value pairs. In some programming languages, these are known as associative arrays or hash tables. Here's the syntax: object \"Application\" { // A dictionary that stores the weight (kg) of each character weight = { \"Surge\" : 35 , \"Neon\" : 30 , \"Charge\" : 37.5 , \"Gimacian\" : 70 }; // print the weights state \"main\" { Console . print ( \"Surge weighs \" + weight [ \"Surge\" ] + \" kg.\" ); Console . print ( \"Neon weighs \" + weight [ \"Neon\" ] + \" kg.\" ); Console . print ( \"Charge weighs \" + weight [ \"Charge\" ] + \" kg.\" ); Console . print ( \"Gimacian weighs \" + weight [ \"Gimacian\" ] + \" kg.\" ); } } Dictionaries have many interesting properties and operations that you can see in the Language Reference . Caution! Whenever you define an array or a dictionary, you spawn a new object. You are advised to NOT define arrays or dictionaries within states, because the code within the states run continuously. New objects will be created at every frame, not just once. object \"Application\" { // arr will be instantiated once the object is created arr = [ 1 , 2 , 3 ]; // RIGHT! state \"main\" { // err is instantiated at every frame of the application, // thus memory is wasted with duplicate objects err = [ \"don't\" , \"do\" , \"this\" ]; // AVOID! } } Casting You can use type-casting to change the type of values from number to string, from string to number, from boolean to string and so on. Casting values is as simple as calling Number(value) , String(value) or Boolean(value) . Example: // Convert string to number str = \"2\" ; val = Number ( str ); // val is 2 // Convert number to string val = 123 ; str = String ( val ); // str is \"123\" When converting an object to a string, SurgeScript will implicitly call object.toString() . Scoping Variables that are defined before any state or function are object-level variables. They can be accessed throughout the whole object. On the other hand, variables used exclusively inside states or functions are local variables . This means that their accessibility and lifespan is restricted to their own locus of code. object \"Scope Test\" { name = \"Surge the Rabbit\" ; // object-level variable state \"main\" { weight = 35 ; // local variable state = \"print-data\" ; // change the state } state \"print-data\" { Console . print ( name ); // Surge the Rabbit Console . print ( weight ); // ERROR: weight is not defined } } Furthermore, object-level variables may only be accessed within the object. Other objects may not read or write the variables directly (in other words, variables are private to the objects). You need to define functions or getters and setters to accomplish that.","title":"Variables"},{"location":"tutorials/variables/#variables","text":"","title":"Variables"},{"location":"tutorials/variables/#introduction","text":"Variables are used to store data. SurgeScript features five basic types: number, string, boolean, null and object. Variables can also point to more complex data structures (such as arrays and dictionaries), but these are always objects.","title":"Introduction"},{"location":"tutorials/variables/#types","text":"","title":"Types"},{"location":"tutorials/variables/#basic-types","text":"Type Description Examples Number A floating-point number 1 , 2 , -3 , 3.14159 String Some text \"Hello, world!\" , 'single-quoted' Boolean True or false true , false Object Reference to an object Application , this , [ ] Null An empty value null As an example, the script below features an object with 3 variables that may be accessed throughout the whole object: object \"Application\" { name = \"Surge the Rabbit\" ; age = 23 ; underage = false ; state \"main\" { Console . print ( name ); // Surge the Rabbit Console . print ( age ); // 23 } }","title":"Basic types"},{"location":"tutorials/variables/#abstract-types","text":"","title":"Abstract types"},{"location":"tutorials/variables/#arrays","text":"Arrays are collections of values that you may access using a zero-based index. Example: object \"Application\" { // The 'characters' array holds 3 strings characters = [ \"Surge\" , \"Neon\" , \"Charge\" ]; state \"main\" { // who are the characters? Console . print ( \"The characters are:\" ); Console . print ( characters [ 0 ]); // will print Surge Console . print ( characters [ 1 ]); // will print Neon Console . print ( characters [ 2 ]); // will print Charge // how many characters? Console . print ( \"Number of characters:\" ); Console . print ( characters . length ); // will print 3 } } Arrays have many interesting properties and operations that you can see in the Language Reference .","title":"Arrays"},{"location":"tutorials/variables/#dictionaries","text":"Dictionaries are collections of key-value pairs. In some programming languages, these are known as associative arrays or hash tables. Here's the syntax: object \"Application\" { // A dictionary that stores the weight (kg) of each character weight = { \"Surge\" : 35 , \"Neon\" : 30 , \"Charge\" : 37.5 , \"Gimacian\" : 70 }; // print the weights state \"main\" { Console . print ( \"Surge weighs \" + weight [ \"Surge\" ] + \" kg.\" ); Console . print ( \"Neon weighs \" + weight [ \"Neon\" ] + \" kg.\" ); Console . print ( \"Charge weighs \" + weight [ \"Charge\" ] + \" kg.\" ); Console . print ( \"Gimacian weighs \" + weight [ \"Gimacian\" ] + \" kg.\" ); } } Dictionaries have many interesting properties and operations that you can see in the Language Reference . Caution! Whenever you define an array or a dictionary, you spawn a new object. You are advised to NOT define arrays or dictionaries within states, because the code within the states run continuously. New objects will be created at every frame, not just once. object \"Application\" { // arr will be instantiated once the object is created arr = [ 1 , 2 , 3 ]; // RIGHT! state \"main\" { // err is instantiated at every frame of the application, // thus memory is wasted with duplicate objects err = [ \"don't\" , \"do\" , \"this\" ]; // AVOID! } }","title":"Dictionaries"},{"location":"tutorials/variables/#casting","text":"You can use type-casting to change the type of values from number to string, from string to number, from boolean to string and so on. Casting values is as simple as calling Number(value) , String(value) or Boolean(value) . Example: // Convert string to number str = \"2\" ; val = Number ( str ); // val is 2 // Convert number to string val = 123 ; str = String ( val ); // str is \"123\" When converting an object to a string, SurgeScript will implicitly call object.toString() .","title":"Casting"},{"location":"tutorials/variables/#scoping","text":"Variables that are defined before any state or function are object-level variables. They can be accessed throughout the whole object. On the other hand, variables used exclusively inside states or functions are local variables . This means that their accessibility and lifespan is restricted to their own locus of code. object \"Scope Test\" { name = \"Surge the Rabbit\" ; // object-level variable state \"main\" { weight = 35 ; // local variable state = \"print-data\" ; // change the state } state \"print-data\" { Console . print ( name ); // Surge the Rabbit Console . print ( weight ); // ERROR: weight is not defined } } Furthermore, object-level variables may only be accessed within the object. Other objects may not read or write the variables directly (in other words, variables are private to the objects). You need to define functions or getters and setters to accomplish that.","title":"Scoping"}]}
\ No newline at end of file
diff --git a/sitemap.xml b/sitemap.xml
index f6415aa..7c493c5 100644
--- a/sitemap.xml
+++ b/sitemap.xml
@@ -2,377 +2,377 @@
https://docs.opensurge2d.org/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/download/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/actor/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/androidplatform/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/animation/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/behavior/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/brick/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/camera/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/circular_movement/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/collider/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/collisionball/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/collisionbox/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/delayedevent/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/directional_movement/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/enemy/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/entity/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/entityevent/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/event/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/eventchain/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/eventlist/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/functionevent/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/game/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/input/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/lang/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/level/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/mobile_gamepad/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/mouse/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/music/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/platform/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/platformer/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/player/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/prefs/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/screen/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/sensor/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/sound/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/surgeengine/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/text/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/transform/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/vector2/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/video/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/engine/web/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/application/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/arguments/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/array/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/boolean/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/console/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/date/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/dictionary/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/gc/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/iterator/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/math/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/number/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/object/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/plugin/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/string/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/surgescript/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/system/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/tags/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/reference/time/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/advanced_features/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/best_practices/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/comments/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/components/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/conditionals/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/expressions/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/functions/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/hello/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/loops/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/object_tree/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/objects/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/packages/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/properties/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/tags/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/testing/
- 2024-05-17
+ 2024-06-24
daily
https://docs.opensurge2d.org/tutorials/variables/
- 2024-05-17
+ 2024-06-24
daily
\ No newline at end of file
diff --git a/sitemap.xml.gz b/sitemap.xml.gz
index aa64039..87e0254 100644
Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ