PlayerScript

PlayerScript is a script that runs within a player. Unlike ItemScript, which is executed in a distributed manner, PlayerScript is guaranteed to run on the specific player’s device. Therefore, it provides real-time access to overlay UI for the device’s screen (PlayerLocalUI), raw input values from the device or controller, avatar movement controls, and more.

One notable use of PlayerScript is the fine control of avatar actions on a per-frame basis.

PlayerScript to speed up player falling:

_.onFrame(dt => {
    if (_.getAvatarMovementFlags() & 0x0001 !== 0) {
        const pos = _.getPosition();
        pos.y -= dt;
        _.setPosition(pos);
    }
});

Another use case is extending the HUD using PlayerLocalUI. By utilizing components like PlayerLocalObjectReferenceList, you can create UIs that are displayed only on the player’s device.

Since PlayerScript excels at controlling both devices and avatars closely, device type detection methods such as _.isVr are also available.

Setting up and executing PlayerScript

PlayerScript associated with an item can be linked to a player and executed by calling the setPlayerScript API from an ItemScript. Only one PlayerScript can be linked to a single player at a time. If there is already an existing PlayerScript running, it will be terminated, and then the new PlayerScript will start. In this case, any variables in memory are not carried over, and the new script starts as a fresh instance.

PlayerScript follows the lifecycle below:

  1. (PlayerScript is linked to a player and starts execution)
  2. All PlayerScript operations
  3. (Execution ends; the player disappears from the space instance, is overwritten by another PlayerScript, or the item that held the PlayerScript disappears)

PlayerScript operates independently from the Owner ownership mechanism. During steps 1 to 3, it will not be transferred to another player’s device, nor will variables in memory be lost.

As a result, PlayerScript does not have an equivalent to $.state from ItemScript, allowing you to write it in a manner closer to standard JavaScript.