Note Starting with Lumberyard 1.8, Lua scripts use the new behavior context that replaces the legacy script context. Scripts that were written before the integration of the behavior context no longer work in Lumberyard versions 1.8 and later. For information on updating code from legacy script context to the new behavior context, see the. For information on the behavior context, see. Adding Lua Scripts to Component Entities Lumberyard makes it easy for you to add script functionality to your game entities by using the Lua Script component. The following steps show you how to do this in Lumberyard Editor. To add a Lua script to a component entity in Lumberyard Editor.
With the Entity Inspector view pane visible, select the entity in the viewport. Click Add Component, and then open Scripting, Lua Script. A Properties table, copied from the script table's Properties table. Default values are provided where appropriate. An entityId property, which contains an object of type EntityId that refers to the current entity.
An IsMaster function, callable by the script, to check whether the currently executing script is on the master node or a proxy node. This function is available only if the script component is network enabled. Built-in Types and Methods The Lumberyard engine provides a number of types and methods that are useful for making games. Many of the types and methods available are listed in the class view available in Lumberyard's Lua IDE. For more information on the class view, see.
Properties The Properties table configures the editor interface for customizing the behavior of a script. With the properties table, users can modify numeric values, select states, and turn flags on and off. The table can even provide a reference to entities that your script can interact with. The properties inside the Properties table are exposed to the editor. Properties outside the Properties table are private and not displayed in the editor. The following example is a properties table from the Controllable Chicken sample level.
The type that you provide as the default value determines how the property is appears in the editor user interface. You can further customize the representation of the property in the editor by specifying additional attributes in a table format. All property types support a description field that appears when you pause your mouse on the property name in the editor. Supported Types Properties can have the types described in this section. Boolean Values (True, False) The following examples are Boolean values.
Self.NetRPCs.RPCNoParam self.NetRPCs.RPCParam(1.0) Communicating with Components Components provide interfaces that allow scripts to send them information and receive notifications when certain actions take place. Communication is established by creating two different objects in Lua: senders and handlers. A sender or a handler is an interface to an, a communication system used extensively in the Lumberyard Engine. When a sender is created, it can call functions, which in turn send information to a component. When a handler is created, the component calls certain functions that the Lua script defines.
These senders and handlers are created with an entity ID. You can use the entity ID to communicate with components that are attached to entities other than the one the script itself is running on.
The main script table always provides a field called entityId that contains the ID of the entity to which the script is attached. Other entity IDs can be passed to the script through the Properties interface. Order of Component Activation Keep in mind the following points regarding the order of activation of Lua components. Lua components are activated after all C components have been activated.
If an entity has multiple Lua components, there is no guarantee regarding which Lua component is activated first. Registering with a Component to Receive Notifications When a Lua script creates a handler object, it notifies a component attached to an entity that it should call the script handler functions when certain events occur. For example, in the first sample below, the script creates a notification bus handler when OnActivate is called. This tells the spawner component attached to the entity that has the script to call the OnSpawnBegin, OnSpawnEnd, and OnEntitySpawned functions when the spawner instantiates a new.
Subsequently, the handler is explicitly disconnected and set back to nil in the OnDeactivate function. This ensures that processing time is not wasted when the entity attached to the script isn't active. As long as the entity is active, these functions are called by the spawner component at the appropriate time. The following code example shows a spawner component handler.
Function samplescript:OnActivate - Retrieve the object's local transform and store it for later use self.myOldTransform = TransformBus.Event.GetLocalTM(self.entityId) - Reset the object's local transform to the identity matrix TransformBus.Event.SetLocalTM(self.entityId, Transform.CreateIdentity) end Communicating with Components Attached to Other Entities You can also send events and create handlers to communicate with components that are attached to other entities. The following example defines a parent entity in the properties table and requests its transform. This allows it to set its transform to that of another entity. The following example code shows the use of a parent entity. Function SampleScript:DoStuff - This value should never be negative assert( self.positiveValue = 0, 'Expected a positive value!
Self.positiveValue ) end - Console output when the value of self.positiveValue is -5: - Error Lua error (2 - string 'q:/lyengine/branches/systems/dev/samplespro.' :61: Expected a positive value! Got: -5) during call samplescript:DoStuff - ALTERNATIVE SYNTAX: function SampleScript:DoStuff - This value should never be negative Debug.Assert( self.positiveValue = 0, 'Expected a positive value! Self.positiveValue ) end - Console output when the value of self.positiveValue is -5: - Error Assert on argument 0: Expected a positive value! Got: -5 Communicating Errors You can use the Debug.Error function to display an error in the console and halt execution of the current script function. This does not halt all execution of the script. If you have active handlers, they can still be called when the engine posts notifications.
The Debug.Error function takes arguments similar to the Debug.Assert function: a condition and a message. The message is displayed in bright red and execution halts only if the condition is false. The following example shows the use of the Debug.Error function. Function SampleScript:CheckAndError - This value should never be negative Debug.Error( self.positiveValue = 0, 'Detected a negative value: '. Self.positiveValue ) end - Console output when the value of self.positiveValue is -5: - Error Error on argument 0: Detected a negative value: -5 Displaying a Warning When User Attention Is Required A script condition can occur that does not adversely affect the execution of the script but might be useful for the user to know about. The Debug.Warning function uses arguments similar to those of the Error and Assert functions but just displays an orange warning message in the console.
It does not halt execution. The following example shows the use of the Debug.Warning function.
Function SampleScript:CheckValue - This value should probably never be negative Debug.Warning( self.positiveValue = 0, 'Detected a negative value: '. Self.positiveValue ) end - Console output when the value of self.positiveValue is -5: - Warning Warning on argument 0: Detected a negative value: -5 The Lua Environment (Advanced) By default, the Lumberyard component entity Lua environment is a single Lua environment (or luaState). This environment is bound to the BehaviorContext that is owned by the ComponentApplication. Because of this, it has access to all API operations that are reflected on startup. Adding Other VMs You may add more ScriptContext instances using the ScriptSystemBus (either call AddContextWithId, or create your own and call AddContext). If you want your new context to be available for debugging, you must register it with ScriptDebugAgentBus::RegisterContext. Reusing Code Lua provides the capability to load and execute scripts from other Lua files using the built-in Lua function.
It's important to note that this function requires a special path format. The file path is delimited by periods instead of slashes, has no.lua file name extension, and is relative to the Lumberyard assets directory. For example, if you want to use the require function to give your scripts some common functionality from the project's Scripts directory, you can use code similar to the following example.
Game Nodes These nodes offer game-specific MBT functionality. These allow a game with multiple character types to trigger specific logic and perform actions involving each type's peculiarities.
Game-specific nodes not likely to be good for 'general use' will probably need customization for each game. Character types are defined in a Lua file, which contains a table of settings for game nodes. InflateAgentCollisionRadiusUsingPhysicsTrick Enlarges an AI agent's capsule radius for collisions with a player. This node employs a trick in the physics system inflate the capsule radius for agent-player collisions while leaving the radius unchanged for collisions between the agent and the world. Sets the player dimensions with the agent-vs.-player collision radius. The physics system is multi-threaded, so there's a short wait while until the player dimensions are committed.
Periodically inspects the player dimensions to check that the agent-vs.-player collision radius has been successfully committed. This can sometimes fail to happen, such as when the AI agent is in a tight spot and can't inflate. Once the agent-vs.-player radius has been committed, goes into the geometry and sets the capsule's radius in place, using the agent-vs.-world radius. This will not affect the agent-vs.-player dimensions. KeepTargetAtADistance Keeps the live target at a distance by physically pushing the target away when it is within a specified distance.
This node is useful when there is some sort of action close to the player and you want to avoid clipping through the camera. Use of this node is preferable over increasing the AI agent's capsule size, which will also affect how the character fits through tight passages.
This node is generally used in parallel with other actions that need to be performed while the player cannot come too close to the AI agent; for example, when playing an animation on the spot that can move the AI agent without moving the locator, causing camera clipping. Target Target of the melee attack. This parameter could be set with the AI agent's AttentionTarget or a generic RefPoint.
CylinderRadius Radius of the cylinder used for the collision check of the hit. HitType Type of hit that will be reported to the game rules. Default is CGameRules::EHitType::Melee. FailIfTargetNotInNavigationMesh Boolean indicating whether or not the node should try to melee a target that is outside the navigation mesh. MaterialEffect Name of the material effect used when the melee attack hits the target.
Success/Failure This node succeeds regardless of whether or not a melee attack is executed and, if it is, whether or not the attack damages the target. This is because a failure in this node is not important for behavior tree logic. If it's important for the game to react to this situation, a fail option can be added.
Multiplayer Pool Game Script Documentary
Damage Amount of damage a melee attack inflicts on the target. HitRange Height of the cylinder used to check whether or not the melee attack can hit the target. KnockdownChance Probability that a successful melee attack knocks down the player. Impulse Amount of impulse applied to the player in the case of a successful melee attack. AngleThreshold Maximum angle allowed between the AI agent's direction of movement and the direction of a path between the AI agent and the target for melee attack to be attempted. ScorcherDeploy Manages how the Scorcher character type handles certain activity while deploying or undeploying as part of its shooting phase. This node relies on some external Lua scripts and various signals to work properly, but is useful in obfuscating some common functionality in the AI libraries.
Before and after the node runs, the following Lua functions are called: EnterScorchTargetPhase and LeaveScorchTargetPhase. When the node starts running, the 'ScorcherScorch' animation tag is requested by Mannequin. When the node stops, if it stops normally, the 'ScorcherNormal' tag is requested again.
If it is terminated prematurely, it is up to the behavior tree script to define a proper exit strategy, such as requesting the 'ScorcherTurtle' tag. On requesting animation tags, the node waits for the following animation events to be received (this ensures that the transition blend animations are not interrupted). 'ScorcherDeployed' – when the scorcher is ready to start firing. 'ScorcherUndeployed' – when the scorcher is again ready to walk around The node encapsulates the following child nodes: RunWhileDeploying and RunWhileDeployed, each of which can contain exactly one child node.
RunWhileDeploying Causes activity to happen while the Scorcher is in the process of deploying, that is, getting ready for an attack. As an example, this node might be used to control aiming before actually shooting. The node will continue running until one of the following events occur, after which the node will be forcefully stopped. ScorcherFriendlyFireWarningModule sends one of these signals to the entity: 'OnScorchAreaClear' or OnScorchAreaNotClearTimeOut'. Mannequin animation sequence sends a 'ScorcherDeployed' signal. An internal timeout elapses The node does not support any parameters. The node SUCCEEDS or FAILS depending on whether the child node succeeds or fails.
The node is allowed to SUCCEED prematurely. RunWhileDeployed Controls actual aiming and firing during an attack. Duration and execution of the attack is controlled via this node. The node does not support any parameters. The node SUCCEEDS or FAILS depending on whether the child node succeeds or fails.
Multiplayer Pool Game
The node is allowed to SUCCEED prematurely. If the node SUCCEEDS, this triggers the parent node to start the undeployment sequence.