Difference between revisions of "Mod:Function"
From Roll20 Wiki
(→sendPing) |
(→spawnFx) |
||
Line 376: | Line 376: | ||
=== <code>spawnFx</code> === | === <code>spawnFx</code> === | ||
+ | {{function parameters | ||
+ | |left | ||
+ | |''(Number)'' The x-coordinate to place the particle emitter. | ||
+ | |top | ||
+ | |''(Number)'' The y-coordinate to place the particle emitter. | ||
+ | |type | ||
+ | |''(String)'' The type of particle emitter to place. For built-in effects, this should be <code>"type-color"</code>, where ''type'' is one of <code>beam</code>, <code>bomb</code>, <code>breath</code>, <code>bubbling</code>, <code>burn</code>, <code>burst</code>, <code>explode</code>, <code>glow</code>, <code>missile</code>, <code>nova</code>, or <code>splatter</code> and ''color'' is one of <code>acid</code>, <code>blood</code>, <code>charm</code>, <code>death</code>, <code>fire</code>, <code>frost</code>, <code>holy</code>, <code>magic</code>, <code>slime</code>, <code>smoke</code>, or <code>water</code>. For custom effects, this should be the <code>id</code> of the FX [[API:Function documentation/Roll20 object|Roll20 object]]. | ||
+ | |page_id | ||
+ | |''(String, optional)'' The id of the page [[API:Function documentation/Roll20 object|Roll20 object]] to place the particle emitter on. If omitted, <code>Campaign().get('playerpageid')</code> will be used instead.}} | ||
+ | {{returns}} | ||
+ | ==== Examples ==== | ||
+ | <pre data-language="javascript">spawnFx(1400, 1400, 'bubbling-acid');</pre> | ||
+ | |||
=== <code>spawnFxBetweenPoints</code> === | === <code>spawnFxBetweenPoints</code> === | ||
=== <code>spawnFxWithDefinition</code> === | === <code>spawnFxWithDefinition</code> === |
Revision as of 07:10, 29 July 2016
Roll20 makes a number of functions available that are not part of core JavaScript or some other library.
Global variables
Variable | Description |
---|---|
_
|
This is the namespace object for the Underscore.js library. |
state
|
Properties of the state object will persist between game sessions. |
_
(Underscore)
This is the namespace object for the Underscore.js library. Underscore has many functions for collection manipulation.
state
Properties of the state object will persist between game sessions. The same state object is also shared between all API scripts in a campaign, so it is strongly recommended that when writing values to state, you minimize your footprint as much as possible in order to avoid name collisions. Note: state gets serialized with JSON, so you cannot store functions or objects with cyclical references.
Global functions
Return type | Function | Description |
---|---|---|
Roll20 object | Campaign
|
Gets the singleton Campaign Roll20 object. |
Roll20 object | createObj
|
Creates a new Roll20 object. |
Array of Roll20 objects | filterObjs
|
Gets all Roll20 objects which pass a predicate test. |
Array of Roll20 objects | findObjs
|
Gets all Roll20 objects with properties that match a given set of attributes. |
Array of Roll20 objects | getAllObjs
|
Gets all Roll20 objects in the campaign. |
varies | getAttrByName
|
Gets the current or max value of an attribute Roll20 object. |
Roll20 object | getObj
|
Gets a specific Roll20 object. |
log
|
Logs a message to the API console. | |
on
|
Registers an event handler. | |
Boolean | playerIsGM
|
Checks whether a player currently has GM privileges. |
playJukeboxPlaylist
|
Start playing a jukebox playlist. | |
Number | randomInteger
|
Generates a random integer value. |
sendChat
|
Sends a chat message. | |
sendPing
|
Sends a ping similar to holding the left mouse button. | |
spawnFx
|
Spawns a particle emitter. | |
spawnFxBetweenPoints
|
Spawns a particle emitter that moves from one point to another. | |
spawnWithDefinition
|
Spawns a particle emitter that is not represented by an FX Roll20 object. | |
stopJukeboxPlaylist
|
Stops all currently playing jukebox playlits. | |
toBack
|
Moves a graphic Roll20 object below all of the other graphics on the same tabletop layer. | |
toFront
|
Moves a graphic Roll20 object above all of the other graphics on the same tabletop layer. |
Campaign
Parameters
No parameters
Returns
The singleton campaign Roll20 object.
Examples
var currentPageID = Campaign().get('playerpageid'), currentPage = getObj('page', currentPageID);
createObj
Parameters
- type
- (String) The type of Roll20 object to create. Only 'graphic', 'text', 'path', 'character', 'ability', 'attribute', 'handout', 'rollabletable', 'tableitem', and 'macro' may be created.
- attributes
- (Object) The initial values to use for the Roll20 object's properties.
Returns
The Roll20 object that was created.
Examples
When creating a Roll20 object that has a parent object (such as creating an attribute Roll20 object, which is a child of a character Roll20 object), you must supply the id of the parent in attributes
.
on('add:character', function(obj) { createObj('attribute', { name: 'Strength', current: 0, max: 30, characterid: obj.id }); });
When creating a path Roll20 object, you must supply a value for the read-only property _path
. This is an exception to the rule that prevents you from setting the value of read-only properties when creating Roll20 objects.
createObj('path', { left: 7000, top: 140, width: 140, height: 140, layer: 'objects', path: JSON.stringify([['M', 0, 0], ['L', 70, 0], ['L', 0, 70], ['L', 0, 0]]) });
When creating a handout Roll20 object, you cannot set the text or gmnotes at the time of creation.
var handout = createObj('handout', { name: 'A Letter Addressed to You', inplayerjournals: 'all', archived: false }); handout.set({ notes: 'Notes can only be set after the handout is created', gmnotes: 'GM Notes can only be set after the handout is created' });
filterObjs
Parameters
- callback
- (Function) A predicate function to test all Roll20 objects against. The callback function receives a Roll20 object as a parameter, and should return either
true
(for Roll20 objects that will be included in the filterObjs return value) orfalse
(for all other Roll20 objects).
Returns
An array of Roll20 objects which passed the predicate test.
Examples
var tokenName = getMyTokenName(), duplicateTokens = filterObjs(function(obj) { if (obj.get('type') !== 'graphic' || obj.get('subtype') !== 'token' || obj.get('name') === tokenName) return false; return obj.get('name').indexOf(tokenName) === 0 && /\d+$/.text(obj.get('name')); });
findObjs
Parameters
- attributes
- (Object) A collection of key:value pairs to match with Roll20 objects in the campaign.
- options
- (Object, optional) If
options.caseInsensitive
istrue
, string comparisons between Roll20 objects andattributes
will be case-insensitive.
Returns
An array of Roll20 objects with properties that match attributes
.
Examples
var npcs = findObjs({ type: 'character', controlledby: '' });
getAllObjs
Parameters
No parameters
Returns
An array of all Roll20 objects in the campaign.
Examples
var everything = getAllObjs();
getAttrByName
Parameters
- character_id
- (String) The id of the character Roll20 object that is the parent of the attribute Roll20 object you want the value of.
- attribute_name
- (String) The name of the attribute Roll20 object you want the value of.
- value_type
- (String, optional) Either
"current"
or"max"
(defaults to "current" if omitted).
Returns
The current
or max
property of the appropriate attribute. If the desired property is not set, the default value specified by the character sheet (if there is a default) will be used instead.
Examples
var character = getMyCharacter(), strength = getAttrByName(character.id, 'strength'), strength_max = getAttrByName(character.id, 'strength', 'max');
getObj
Parameters
- type
- (String) The type of Roll20 object to get.
- id
- (String) The unique id for the Roll20 object to get.
Returns
The specified Roll20 object.
Examples
on('chat:message', function(msg) { var sendingPlayer = getObj('player', msg.playerid); });
log
Parameters
- message
- (varies) The message to post to the API console. The
message
parameter will be transformed into a String withJSON.stringify
.
Returns
(Void)
Examples
on('chat:message', function(msg) { log('Message received from:'); log(getObj('player', msg.playerid)); });
{"_d20userid":"123456","_displayname":"John Doe","speakingas":"","_online":true,"color":"#885b68","_macrobar":"-J16Z-dRU5tleKiKOg0X|-K3F_4q_b1p-Vdiwgn1t","showmacrobar":true,"_id":"-J16Z-dRU5tleKiKOc0X","_type":"player","_lastpage":""}
on
Parameters
- event
- (String) There are five types of event:
- ready
- change
- add
- destroy
- chat
- With the exception of ready, all event types must also be paired with an object type. For chat, this is always message. For everything else, this is the
type
property of a Roll20 object. In addition to the object type, change events can also optionally specify a property of the specified Roll20 object to watch. - The 2-3 parts of the event (type, object, and optionally property) are separated by colons. So, valid
event
strings include but are not limited to "ready", "chat:message", "change:graphic", "change:campaign:playerpageid", "add:character", and "destroy:handout". - callback
- (Function) The function that will be called when the specified event fires. The parameters passed depend on the event type:
- ready events have no callback parameters.
- change events have an
obj
parameter, which is a reference to the Roll20 object as it exists after the change, and aprev
parameter, which is a plain old JavaScript object with properties matching the Roll20 object prior to the change event. - add events have an
obj
parameter, which is a reference to the new Roll20 object. - destroy events have an
obj
parameter, which is a reference to the no-longer existing Roll20 object. - chat events have a
msg
parameter, which contains the details of the message that was sent to the chat.
Returns
(Void)
Examples
Events are fired in the order they were registered, and from most to least specific. In this example, a change to a graphic Roll20 object's left
property will result in function3
getting called, followed by function1
and then function2
.
on('change:graphic', function1); on('change:graphic', function2); on('change:graphic:left', function3);
add events will attempt to fire for Roll20 objects that are already in the campaign when a new session starts. In order to prevent this behavior, you can wait to register your add event until the ready event fires.
on('add:graphic', function(obj) { // When the session begins, this function will be called for every graphic in the campaign // This function will also be called whenever a new graphic Roll20 object is created }); on('ready', function() { on('add:graphic', function(obj) { // This function will *only* be called when a new graphic Roll20 object is created, not for ones that already exist }); });
The pre
parameter for change events is not a Roll20 object, it is a plain old JavaScript object. As such, you cannot use the get
or set
functions, and you cannot omit the leading underscores on read-only properties.
on('change:graphic', function(obj, prev) { var id1 = obj.id, // all three are equivalent id2 = obj.get('id'), id3 = obj.get('_id'), id4 = prev.id, // undefined id5 = prev.get('id'), // undefined is not a function id6 = prev._id; // correct // both are equivalent obj.set('left', 70); obj.set({ left: 70 }); prev.set('left', 70); // undefined is not a function prev.set({ // undefined is not a function left: 70 }); prev.left = 70; // correct, although it won't change anything on the tabletop });
playerIsGM
Parameters
- player_id
- (String) The id of the player Roll20 object to check.
Returns
true
if the player currently has GM permissions, or false
otherwise.
Examples
This function is especially useful for limiting API commands to GM use.
on('chat:message', function(msg) { if (msg.type !== 'api') return; if (msg.content.indexOf('!playercommand') === 0) { // ... } else if (msg.content.indexOf('!gmcommand') === 0) { if (!playerIsGM(msg.playerid)) return; // ... } });
playJukeboxPlaylist
Parameters
- playlist_id
- (String) The id of the playlist to start playing.
Returns
(Void)
Examples
var playlists = JSON.parse(Campaign().get('jukeboxfolder')), myPlaylist = _.find(playlists, (folder) => _.isObject(folder) && folder.n === myPlaylistName); playJukeboxPlaylist(myPlaylist.id);
randomInteger
Parameters
- max
- (Number) The maximum number to return, inclusive.
Returns
A random integer between 1 (inclusive) and max
(inclusive). This function has better distribution than Math.random()
, and is recommended over it. This function doesn't make use of the Quantum Roll feature used by the dice engine, but it does use the same pseudorandom algorithm that the dice engine will fall back on if Quantum Roll is unavailable.
Examples
Because this function returns an integer from 1 to max
, it is ideal for quickly generating a dice roll outcome if you don't need the full strength of Roll20's dice engine.
var d20Result = randomInteger(20); // roughly equivalent to rolling a 20-sided die
sendChat
Parameters
- speakingAs
- (String) The name to attach to the message being sent. If
speakingAs
is in the formatplayer
- player_id or
character
- character_id, the message will be sent as that player or character. Otherwise, the message will use the given name as though a GM had used the /as command.
- message
- (String) The message to send to the chat.
- callback
- (Function, optional) If
callback
is specified, the result of the chat message will be passed to it instead of appearing in the chat. The parameter of the callback method is an array of message Roll20 objects - options
- (Object, optional) If
options.noarchive
istrue
, the message will not be added to the chat archive. Ifoptions.use3d
istrue
, dice rolls in the message will use the 3D dice feature. Options are not applicable ifcallback
is specified.
Returns
(Void)
Examples
sendChat('Example', 'This is a simple example.');
You can easily write code to send a message as the same player or character that triggered a chat:message event.
on('chat:message', function(msg) { var character = findObjs({ type: 'character', name: msg.who })[0], player = getObj('player', msg.playerid), message = ' said something'; if (character) sendChat('character|'+character.id, character.get('name')+message); else sendChat('player|'+player.id, player.get('displayname')+message); });
The callback
parameter is useful if you need to leverage Roll20's dice engine. There is no particular need for a speakingAs
value when using the callback
, since the message won't appear in the chat anyway.
sendChat('', '/r 2d20k1+'+strengthMod, function(ops) { var msg = ops[0]; // ... });
options.noarchive
is primarily designed for sending players menus made from API Command buttons without clogging their chat history.
sendChat('System', '[Clear changes](!clear)\n[Add tile](!add)\n[View sample](!view)\n[Save layout](!save)', null, { noarchive: true });
sendPing
Parameters
- left
- (Number) The x-coordinate to place the ping at.
- top
- (Number) The y-coordinate to place the ping at.
- page_id
- (String) The id of the page Roll20 object to place the ping on.
- player_id
- (String, optional) The ping will use the specified player's color. If
player_id
is omitted, the ping will be yellow. - moveAll
- (Boolean, optional) If
moveAll
istrue
, all of the players on the appropriate page will have their views centered on the ping.
Returns
(Void)
Examples
on('chat:message', function(msg) { var obj; if (msg.type === 'api' && msg.content.indexOf('!ping') === 0) { if (!msg.selected) return; obj = getObj(msg.selected[0]._type, msg.selected[0]._id); sendPing(obj.get('left'), obj.get('top'), obj.get('pageid'), msg.playerid, true); // center everyone on the selected token } });
spawnFx
Parameters
- left
- (Number) The x-coordinate to place the particle emitter.
- top
- (Number) The y-coordinate to place the particle emitter.
- type
- (String) The type of particle emitter to place. For built-in effects, this should be
"type-color"
, where type is one ofbeam
,bomb
,breath
,bubbling
,burn
,burst
,explode
,glow
,missile
,nova
, orsplatter
and color is one ofacid
,blood
,charm
,death
,fire
,frost
,holy
,magic
,slime
,smoke
, orwater
. For custom effects, this should be theid
of the FX Roll20 object. - page_id
- (String, optional) The id of the page Roll20 object to place the particle emitter on. If omitted,
Campaign().get('playerpageid')
will be used instead.
Returns
(Void)
Examples
spawnFx(1400, 1400, 'bubbling-acid');