[Character System](../groups/Character System.Character System.md) / Player
Player Class
Role Manager
Player Contains the Player object currently connected to the MW server. It is responsible for managing various unique identifiers (IDs) of characters and providing functions for creating, acquiring, and managing players.
The character manager class will maintain a dictionary for storing the unique identifiers of all character. Used to distinguish different roles.
The character Manager will provide methods to add, delete, and retrieve character IDs. When creating a new role, the role's ID will be assigned and added to the manager's list. When the character no longer exists, the ID will be deleted from the list. Through these methods, you can easily manage the ID collection of character.
The character manager also provides the function of obtaining players. Through the ID of the Player, you can easily obtain the corresponding character object from the manager. In this way, the code of other parts can use the ID of the Player to obtain the character instance associated with it for further processing and operation.
It is worth noting that the character of the local Player can be obtained through Player.localPlayer.character, and the configuration of the local character Player can be enabled.
Table of contents
Properties
onCharacterAdd: MulticastDelegate <(character : Character ) => void > other |
---|
When the Player's character is create, the binding function is executed |
onCharacterRemove: MulticastDelegate <(character : Character ) => void > other |
When the player's character is removed, execute the binding function |
onPlayerAdd: MulticastDelegate <(player : Player ) => void > other |
When adding a player, execute the binding function |
onPlayerDisconnect: MulticastDelegate <(player : Player ) => void > other |
Player disconnects commission |
onPlayerReconnect: MulticastDelegate <(player : Player ) => void > other |
Player reconnection delegate |
onPlayerRemove: MulticastDelegate <(player : Player ) => void > other |
When the Player is removed, execute the binding function |
onUserAvatarUpdated: MulticastDelegate <() => void > other |
When the appearance of the user platform changes, execute the binding function |
Accessors
character(): Character other |
---|
Control role |
nickname(): string other |
Player nickname |
ping(): number other |
It is used to record and display the network delay of Player. |
playerId(): number other |
Player ID |
teamId(): string other |
Team ID |
teleportId(): string other |
Transfer ID |
userId(): string other |
User Platform ID |
localPlayer(): Player other |
The Player whose client is running. |
Methods
control(pawn : Pawn ): boolean other |
---|
Control a Pawn object |
getPlayerState<T : extends PlayerState <T >>(type : (...args : unknown []) => T : extends PlayerState <T >): T : extends PlayerState <T > other |
Get PlayerState instance |
asyncGetLocalPlayer(): Promise <Player > other |
Asynchronous acquisition of local players. |
asyncGetPlayer(uniqueId : string number ): Promise <Player > other |
Asynchronous acquisition of players |
getAllPlayers(): Player [] other |
Get all current Player. |
getControllerRotation(outer? : Rotation ): Rotation other |
Obtain the rotation of the controller |
getPlayer(uniqueId : string number ): Player other |
Get the Player and find the corresponding Player according to the userId |
setControllerRotation(newRotation : Rotation ): void other |
Overtrite the rotation of the controller |
Properties
onCharacterAdd
• Readonly
onCharacterAdd: MulticastDelegate
<(character
: Character
) => void
> other
When the Player's character is create, the binding function is executed
Precautions
After creating a player, the player's character will continue to be created. When the event is triggered, the character's bones and collision bodies have already been created and can start moving, while the appearance and pendants of the character may need to wait for a period of time to be created. If you need to wait for the complete completion of the character, you can use Character: asyncReady to wait, or you can ensure that the character has a complete appearance and attachment by listening to the Character.onDescriptionComplete event.
Usage example: create a script named "Example_Player_onCharacterAdd", place it in the object bar, open the script, enter the following code to save, run the game, and you will bind a function to the [Add Player] event: when a Player joins, listen to the [Add Player character] event. Bind a function to the 'Add Character' event: change the overhead display name of the character to 'John'. The code is as follows:
export default class Example_Player_onCharacterAdd extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
Player.onPlayerAdd.add((player) => {
player.onCharacterAdd.add((character) => {
character.displayName = "John";
});
});
}
}
}
export default class Example_Player_onCharacterAdd extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
Player.onPlayerAdd.add((player) => {
player.onCharacterAdd.add((character) => {
character.displayName = "John";
});
});
}
}
}
onCharacterRemove
• Readonly
onCharacterRemove: MulticastDelegate
<(character
: Character
) => void
> other
When the player's character is removed, execute the binding function
Precautions
This event is triggered before removing the Player's character. At this time, you can recycle the objects attached to the Player's character or access the data on the player's character for archiving.
Usage example: create a script named "Example_Player_onCharacterRemove", place it in the object bar, open the script, enter the following code to save, run the game, and you will bind a function to the [Add Player] event: when Player joins, listen to the [Remove Player character] event. Bind a function to the [Remove Player character] event: create a death effect at the current position of Player character and play it. The code is as follows:
export default class Example_Player_onCharacterRemove extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
Player.onPlayerAdd.add((player) => {
player.onCharacterRemove.add((character) => {
let effect = GameObject.spawn("298313") as Effect;
effect.worldTransform.position = character.worldTransform.position;
effect.play();
});
});
}
}
}
export default class Example_Player_onCharacterRemove extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
Player.onPlayerAdd.add((player) => {
player.onCharacterRemove.add((character) => {
let effect = GameObject.spawn("298313") as Effect;
effect.worldTransform.position = character.worldTransform.position;
effect.play();
});
});
}
}
}
onPlayerAdd
▪ Static
Readonly
onPlayerAdd: MulticastDelegate
<(player
: Player
) => void
> other
When adding a player, execute the binding function
Precautions
This event is triggered when a new Player joins the game and create a Player object. It should be noted that the client cannot listen to the addition of local Player. It is usually recommended to bind the event function to the server.
Usage example: create a script named "Example_Player_onPlayerAdd", place it in the object bar, open the script, enter the following code to save, run the game, and you will bind a function to the [Add Player] event: print the prompt log added by the Player on the console, including the Player ID and the Player's user ID. The code is as follows:
export default class Example_Player_onPlayerAdd extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
Player.onPlayerAdd.add((player) => {
console.log("Player ID " + player.playerId + "User ID " + player.userId);
});
}
}
}
export default class Example_Player_onPlayerAdd extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
Player.onPlayerAdd.add((player) => {
console.log("Player ID " + player.playerId + "User ID " + player.userId);
});
}
}
}
onPlayerDisconnect
▪ Static
Readonly
onPlayerDisconnect: MulticastDelegate
<(player
: Player
) => void
> other
Player disconnects commission
Precautions
Execute binding function when player disconnects. The dual end triggering mechanism for this delegation is different. On the client side, it is only triggered by the local Player's disconnection event, and the trigger time is the instant of disconnection. When triggered by any player disconnection event on the server, if no message is received from the client player within 5 seconds, it is considered disconnected. When the client switches to the background, watches Ads and other OnPause operations, the callback will also be triggered on the server.
Usage example: create a script named "Example_Player_OnPlayer Disconnect", place it in the object bar, open the script, enter the following code to save, run the game, and you will add a function to the [Player disconnected] delegate: print the Player disconnected game message. In the console, you can see the user ID of the disconnected Player and the disconnected notification. The code is as follows:
@Component
export default class Example_Player_OnPlayerDisconnect extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
// Delegate the addition of a function to 'Player Join' to print the message of the player joining the game
Player.onPlayerJoin.add((player) => {
console.log("Player " + player.userId + " joined the Game");
});
// Add a function to the 'Player Departure' delegation to print the message of the player leaving the game
Player.onPlayerLeave.add((player) => {
console.log("Player " + player.userId + " Left the Game");
});
// Add a function to delegate of [Player disconnected] to print Player disconnected message
Player.onPlayerDisconnect.add((player) => {
console.log("Player " + player.userId + " is disconnected");
});
// Add a function to delegate player reconnection to print player reconnection messages
Player.onPlayerReconnect.add((player) => {
console.log("Player " + player.userId + " is reconnected");
});
}
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
// Get the current client's Player (himself)
let myself = Player.localPlayer;
// Add a function to delegate of [Player disconnected] to print Player disconnected message
Player.onPlayerDisconnect.add((player) => {
console.log("Player " + player.userId + " is disconnected");
});
// Add a function to delegate player reconnection to print player reconnection messages
Player.onPlayerReconnect.add((player) => {
console.log("Player " + player.userId + " is reconnected");
});
}
}
}
@Component
export default class Example_Player_OnPlayerDisconnect extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
// Delegate the addition of a function to 'Player Join' to print the message of the player joining the game
Player.onPlayerJoin.add((player) => {
console.log("Player " + player.userId + " joined the Game");
});
// Add a function to the 'Player Departure' delegation to print the message of the player leaving the game
Player.onPlayerLeave.add((player) => {
console.log("Player " + player.userId + " Left the Game");
});
// Add a function to delegate of [Player disconnected] to print Player disconnected message
Player.onPlayerDisconnect.add((player) => {
console.log("Player " + player.userId + " is disconnected");
});
// Add a function to delegate player reconnection to print player reconnection messages
Player.onPlayerReconnect.add((player) => {
console.log("Player " + player.userId + " is reconnected");
});
}
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
// Get the current client's Player (himself)
let myself = Player.localPlayer;
// Add a function to delegate of [Player disconnected] to print Player disconnected message
Player.onPlayerDisconnect.add((player) => {
console.log("Player " + player.userId + " is disconnected");
});
// Add a function to delegate player reconnection to print player reconnection messages
Player.onPlayerReconnect.add((player) => {
console.log("Player " + player.userId + " is reconnected");
});
}
}
}
onPlayerReconnect
▪ Static
Readonly
onPlayerReconnect: MulticastDelegate
<(player
: Player
) => void
> other
Player reconnection delegate
Precautions
When the player reconnects, the binding function is executed, and the disconnection callback will be triggered first. After receiving consecutive client messages, the reconnection callback will be triggered.
Usage example: create a script named "Example_Player_OnPlayerReconnect", place it in the object bar, open the script, enter the following code to save, run the game, and you will add a function to the [Player Reconnect] delegate: print the Player Reconnect Game message. You can see the user ID and reconnection notification of the reconnected Player on the console. The code is as follows:
@Component
export default class Example_Player_OnPlayerReconnect extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
// Delegate the addition of a function to 'Player Join' to print the message of the player joining the game
Player.onPlayerJoin.add((player) => {
console.log("Player " + player.userId + " joined the Game");
});
// Add a function to the 'Player Departure' delegation to print the message of the player leaving the game
Player.onPlayerLeave.add((player) => {
console.log("Player " + player.userId + " Left the Game");
});
// Add a function to delegate of [Player disconnected] to print Player disconnected message
Player.onPlayerDisconnect.add((player) => {
console.log("Player " + player.userId + " is disconnected");
});
// Add a function to delegate player reconnection to print player reconnection messages
Player.onPlayerReconnect.add((player) => {
console.log("Player " + player.userId + " is reconnected");
});
}
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
// Get the current client's Player (himself)
let myself = Player.localPlayer;
// Add a function to delegate of [Player disconnected] to print Player disconnected message
Player.onPlayerDisconnect.add((player) => {
console.log("Player " + player.userId + " is disconnected");
});
// Add a function to delegate player reconnection to print player reconnection messages
Player.onPlayerReconnect.add((player) => {
console.log("Player " + player.userId + " is reconnected");
});
}
}
}
@Component
export default class Example_Player_OnPlayerReconnect extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
// Delegate the addition of a function to 'Player Join' to print the message of the player joining the game
Player.onPlayerJoin.add((player) => {
console.log("Player " + player.userId + " joined the Game");
});
// Add a function to the 'Player Departure' delegation to print the message of the player leaving the game
Player.onPlayerLeave.add((player) => {
console.log("Player " + player.userId + " Left the Game");
});
// Add a function to delegate of [Player disconnected] to print Player disconnected message
Player.onPlayerDisconnect.add((player) => {
console.log("Player " + player.userId + " is disconnected");
});
// Add a function to delegate player reconnection to print player reconnection messages
Player.onPlayerReconnect.add((player) => {
console.log("Player " + player.userId + " is reconnected");
});
}
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
// Get the current client's Player (himself)
let myself = Player.localPlayer;
// Add a function to delegate of [Player disconnected] to print Player disconnected message
Player.onPlayerDisconnect.add((player) => {
console.log("Player " + player.userId + " is disconnected");
});
// Add a function to delegate player reconnection to print player reconnection messages
Player.onPlayerReconnect.add((player) => {
console.log("Player " + player.userId + " is reconnected");
});
}
}
}
onPlayerRemove
▪ Static
Readonly
onPlayerRemove: MulticastDelegate
<(player
: Player
) => void
> other
When the Player is removed, execute the binding function
Precautions
This event is triggered when the player exits the game and prepares to remove the Player object.
Example usage: Create a script called "Instance-Player_onPlayerDemove", place it in the object bar, open the script, enter the following code to save, run the game, and you will bind a function to the "Remove Player" event: print a prompt log on the console for the player to exit, including the player ID and the player's user ID. The code is as follows:
export default class Example_Player_onPlayerRemove extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
Player.onPlayerRemove.add((player) => {
console.log("Player ID " + player.playerId + "User ID " + player.userId);
});
}
}
}
export default class Example_Player_onPlayerRemove extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
Player.onPlayerRemove.add((player) => {
console.log("Player ID " + player.playerId + "User ID " + player.userId);
});
}
}
}
onUserAvatarUpdated
▪ Static
onUserAvatarUpdated: MulticastDelegate
<() => void
> other
When the appearance of the user platform changes, execute the binding function
Precautions
This event is triggered when the Player switches out of the game, enters the character editor, modifies the appearance and saves it, and switches back to the game.
Usage example: create a script named "Example_Player_onUserAvatarUpdated", place it in the object bar, open the script, enter the following code to save, run the game, and you will bind a function to the [User Platform appearance Change] event: request the platform appearance and apply it to the character. The code is as follows:
@Component
export default class Example_Player_onUserAvatarUpdated extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
}
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
Player.onUserAvatarUpdated.add(() => {
AccountService.downloadData(Player.localPlayer.character, () => {}, 0);
});
}
}
}
@Component
export default class Example_Player_onUserAvatarUpdated extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
}
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
Player.onUserAvatarUpdated.add(() => {
AccountService.downloadData(Player.localPlayer.character, () => {}, 0);
});
}
}
}
Accessors
character
• | ||
---|---|---|
Control role Precautions The character control by the Player is a Pawn object. When the Player switches the control character, the client cannot get the latest value immediately. In other cases, as long as the player is obtained, the loaded control character can be obtained simultaneously. Example usage: Create a script named "Instance-Player_Character", place it in the object bar, open the script, enter the following code to save, run the game, you will get the current client player, and see the printed player character's guide and name in the console. The code is as follows: ts
Returns
|
nickname
• | ||
---|---|---|
Player nickname Usage example: create a script named "Example_Player_Nickname", place it in the object bar, open the script, enter the following code to save, run the game, and you will see the printed Player's nickname in the console. The code is as follows: ts
Returns
|
ping
• | ||
---|---|---|
It is used to record and display the network delay of Player. Network delay refers to the time required from Player executing an operation in the game to the operation being displayed in other Player 'games. Usually expressed in milliseconds (ms). Lower latency means that player actions can be quickly transmitted to the server and other players, and the game's response is more immediate. Precautions Network latency of Player client. In milliseconds- 1 indicates acquisition failure. Usage example: create a script named "Example_Player_Ping", place it in the object bar, open the script, enter the following code to save, run the game, you will get the current client Player, and see the printed Player's current Ping value in the console. The code is as follows: ts
Returns
|
playerId
• | ||
---|---|---|
Player ID PlayerID is the runtime ID, which changes every time you enter the game; The userID is a unique identifier for the player's ID and will not change Usage example: create a script named "Example_Player_PlayerId", place it in the object bar, open the script, enter the following code to save, run the game, you will get the current client Player, and see the printed Player Player ID in the console. The code is as follows: ts
Returns
|
teamId
• | ||
---|---|---|
Team ID Precautions Player's team ID (automatically formed by game jump). If the player is not in any team, the value is empty. Usage example: create a script named "Example_Player_TeamId", place it in the object bar, open the script, enter the following code to save, run the game, you will get the current client Player, and see the printed Player's team ID in the console. The code is as follows: ts
Returns
|
teleportId
• | ||
---|---|---|
Transfer ID Precautions Player's transfer ID (automatically formed by transfer). If the player did not enter the current scene through teleportation, the value is empty. Usage example: create a script named "Example_Player_TeleportId", place it in the object bar, open the script, enter the following code to save, run the game, you will get the current client Player, and see the printed Player's team ID in the console. The code is as follows: ts
Returns
|
userId
• | ||
---|---|---|
User Platform ID The user platform ID of the Player. This value is sync at multiple ends and can be used as the unique ID of Player. After the Player object is ready, it needs to wait for a period of time for the value to be ready. Usage example: create a script named "Example_Player_UserId", place it in the object bar, open the script, enter the following code to save, run the game, you will get the current client Player, and see the printed Player's user platform ID in the console. The code is as follows: ts
Returns
|
localPlayer
• |
---|
The Player whose client is running. LocalPlayer It is a read-only attribute. Because it runs on the client side. This property is null for the server on which the Script object runs its code. The player corresponding to the current client. Only the client call returns to the local Player. The server call is invalid and a warning is printed on the console. Usage example: create a script named "Example_Player_LocalPlayer", place it in the object bar, open the script, enter the following code to save, run the game, you will get the Player of the current client in the scene, press the keyboard "1", and you will see the effect of character invisibility for 2 seconds in the scene. The code is as follows: ts
Returns |
Player |
---|
Methods
control
• control(pawn
): boolean
other
Control a Pawn object
Parameters
pawn Pawn | Usage: target control object |
---|
Returns
boolean | Manipulation results |
---|
Usage example: drag the used asset: "7750" into the priority loading column. Create a script named 'Instance-Player_Control', place it in the object bar, open the script, enter the following code to save, run the game, and you will add a 'Create Character and Control' event listener on the server. When an event is detected, create a default character in the scene and control it. Press "1" on the keyboard to send the event [create character and control] to the server. Add a function to the local Player's [Player control object change] delegate: play a effect at the position of the new character generate and control. The binding function is executed when the control object change delegate is triggered. The code is as follows:
@Component
export default class Example_Player_Control extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
// Add a 'Create Role and Control' event listener on the server
mw.Event.addClientListener("SpawnCharacterAndControl", (player) => {
let newPawn = Player.spawnDefaultCharacter();
newPawn.worldTransform.position = new Vector(200, 0, 500);
player.control(newPawn);
});
}
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
// Get the current client's Player (himself)
let myPlayer = Player.localPlayer;
// Add a function to the local Player's [Player control object change] delegate: play a effect at the position of the new character generate and control
myPlayer.onPawnChange.add((pawn) => {
EffectService.playAtPosition("7750", new Vector(200, 0, 500));
});
// Add a key method: press "1" on the keyboard to send an event to the server [create character and control]
InputUtil.onKeyDown(Keys.One, () => {
mw.Event.dispatchToServer("SpawnCharacterAndControl");
});
}
}
}
@Component
export default class Example_Player_Control extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
// Add a 'Create Role and Control' event listener on the server
mw.Event.addClientListener("SpawnCharacterAndControl", (player) => {
let newPawn = Player.spawnDefaultCharacter();
newPawn.worldTransform.position = new Vector(200, 0, 500);
player.control(newPawn);
});
}
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
// Get the current client's Player (himself)
let myPlayer = Player.localPlayer;
// Add a function to the local Player's [Player control object change] delegate: play a effect at the position of the new character generate and control
myPlayer.onPawnChange.add((pawn) => {
EffectService.playAtPosition("7750", new Vector(200, 0, 500));
});
// Add a key method: press "1" on the keyboard to send an event to the server [create character and control]
InputUtil.onKeyDown(Keys.One, () => {
mw.Event.dispatchToServer("SpawnCharacterAndControl");
});
}
}
}
getPlayerState
• getPlayerState<T
>(type
): T
other
Get PlayerState instance
Parameters
type (...args : unknown []) => T | PlayerState Derived class default: null |
---|
Returns
T | PlayerState instance |
---|
PlayerState The object is used to help the game track and manage Player's personal data. It stores information related to each player, so that the game can access and update this information as needed at any time.
For example, suppose you are playing a multiplayer shoot game. Each Player has a PlayerState object, which contains data such as Player's scores, kills, and deaths. When the Player defeats the enemy, the game will add the score to the corresponding Player's PlayerState. In this way, the game can display the leaderboard or judge the outcome according to each Player's PlayerState.
In general, it is used to track and store data and status related to each player. It helps the game manage Player's personal information, such as score, HP, etc., and ensures sync of Player status in multiplayer games. Through PlayerState, games can better handle individual and team data in multiplayer games to provide a richer gaming experience.
Example usage: Create a script named "PlayerStateExample", place it in the object bar, open the script, enter the following code to save. Change the number of Player in the startup parameter to 2, run the game and press the R key to see one of the clients receive test sync. Press the P key to print the test value of the client.
// Each Player on the server will automatically create an instance when entering the game
export class GamePlayerState extends mw.PlayerState {
@Property({replicated: true, onChanged: "onRepTest"})
test = "";
onRepTest(path: string[], value: string, oldVal: string) {
console.log(`onRepTest path: ${path} value: ${value} oldVal: ${oldVal}`);
}
}
@Component
export default class PlayerStateExample extends mw.Script {
protected onStart(): void {
// Press R to randomly select a player on the server to modify the test property of GamePlayerState
InputUtil.onKeyDown(Keys.R, () => this.random());
// Press P to print the test property of Player GamePlayState on the main control terminal
InputUtil.onKeyDown(Keys.P, () => {
const playerState = Player.localPlayer.getPlayerState(GamePlayerState);
console.log(`test: ${playerState.test}`);
});
}
@RemoteFunction(Server)
random() {
const players = Player.getAllPlayers();
// Random a Player
const luckPlayer = players[Math.floor(Math.random() * players.length)];
// Get GamePlayerState instance
const playerState = luckPlayer.getPlayerState(GamePlayerState);
playerState.test = `random: ${ Math.floor(Math.random() * 100)}`;
}
}
// Each Player on the server will automatically create an instance when entering the game
export class GamePlayerState extends mw.PlayerState {
@Property({replicated: true, onChanged: "onRepTest"})
test = "";
onRepTest(path: string[], value: string, oldVal: string) {
console.log(`onRepTest path: ${path} value: ${value} oldVal: ${oldVal}`);
}
}
@Component
export default class PlayerStateExample extends mw.Script {
protected onStart(): void {
// Press R to randomly select a player on the server to modify the test property of GamePlayerState
InputUtil.onKeyDown(Keys.R, () => this.random());
// Press P to print the test property of Player GamePlayState on the main control terminal
InputUtil.onKeyDown(Keys.P, () => {
const playerState = Player.localPlayer.getPlayerState(GamePlayerState);
console.log(`test: ${playerState.test}`);
});
}
@RemoteFunction(Server)
random() {
const players = Player.getAllPlayers();
// Random a Player
const luckPlayer = players[Math.floor(Math.random() * players.length)];
// Get GamePlayerState instance
const playerState = luckPlayer.getPlayerState(GamePlayerState);
playerState.test = `random: ${ Math.floor(Math.random() * 100)}`;
}
}
Type parameters
T | extends PlayerState <T > |
---|
asyncGetLocalPlayer
• Static
asyncGetLocalPlayer(): Promise
<Player
> other
Asynchronous acquisition of local players.
Returns
Promise <Player > | Return to local Player |
---|
It is usually used in UI script. When obtaining the local Player character that has not been create, this asynchronous loading API will be used. The maximum waiting time is 10 seconds, and then the local character will be loaded.
When obtaining local Player normally, use Player.localPlayer.
This asynchronous method is only required in UI scripts to obtain localPlayer. Only the client call returns to the local Player. The server call is invalid and a warning is printed on the console.
asyncGetPlayer
• Static
asyncGetPlayer(uniqueId
): Promise
<Player
> other
Asynchronous acquisition of players
Parameters
uniqueId string number | Usage: player ID range: determined by player ID type: integer |
---|
Returns
Promise <Player > | Player Object |
---|
Usage example: create a script named "Example_Player_GetPlayer", place it in the object bar, open the script, enter the following code to save, run the game, you will get the Player through the getPlayer API, press the keyboard "1", use the getPlayer function to get the Player object through userId or playerId, and print the name to see the effect of getPlayer in the console. The code is as follows:
@Component
export default class Example_Player extends Script {
protected onStart(): void {
Player.asyncGetPlayer(Player.localPlayer.playerId).then((player)=>{
console.log(player.playerId)
});
}
}
@Component
export default class Example_Player extends Script {
protected onStart(): void {
Player.asyncGetPlayer(Player.localPlayer.playerId).then((player)=>{
console.log(player.playerId)
});
}
}
getAllPlayers
• Static
getAllPlayers(): Player
[] other
Get all current Player.
Returns
Player [] | Array of all Player in the server |
---|
This method returns the array of all currently connected Player. When used in combination with the for loop, it is very useful for iterating all Player in the game.
Usage example: Drag the resource "27087" into the priority loading bar. Create a script named "Example_Player_GetAllPlayers", place it in the object bar, open the script, enter the following code to save, run the game, and you will add an event listener named "Print all Player 'information in the game" to the server. After listening to the event, you will see the effect of a crown generate above the head of Player' character and print the userIDs of Player on the console. When you encounter the client Player who initiated the event, you will be prompted prompt. The code is as follows:
@Component
export default class Example_Player_GetAllPlayers extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
// Add an event listener [Print all Player 'information in the game] on the server
mw.Event.addClientListener("PrintPlayersInfo", (player) => {
// Traverse the Players array, print their userId, prompt 'This is me' when encountering the client player who initiated the event, and generate a crown on top of the player character's head
Player.getAllPlayers().forEach((value) => {
if(value.playerId == player.playerId) {
console.log(" Player " + player.userId + " This is me");
let crown = GameObject.spawn<Model>("27087");
crown.setCollision(CollisionStatus.Off);
value.character.attachToSlot(crown, HumanoidSlotType.Rings);
} else {
console.log(" Player " + player.userId);
}
});
});
}
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
// Add a key method: press "1" on the keyboard to send an event to the server [print all Player 'information in the game]
InputUtil.onKeyDown(Keys.One, () => {
mw.Event.dispatchToServer("PrintPlayersInfo");
});
}
}
}
@Component
export default class Example_Player_GetAllPlayers extends Script {
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the server side
if(SystemUtil.isServer()) {
// Add an event listener [Print all Player 'information in the game] on the server
mw.Event.addClientListener("PrintPlayersInfo", (player) => {
// Traverse the Players array, print their userId, prompt 'This is me' when encountering the client player who initiated the event, and generate a crown on top of the player character's head
Player.getAllPlayers().forEach((value) => {
if(value.playerId == player.playerId) {
console.log(" Player " + player.userId + " This is me");
let crown = GameObject.spawn<Model>("27087");
crown.setCollision(CollisionStatus.Off);
value.character.attachToSlot(crown, HumanoidSlotType.Rings);
} else {
console.log(" Player " + player.userId);
}
});
});
}
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
// Add a key method: press "1" on the keyboard to send an event to the server [print all Player 'information in the game]
InputUtil.onKeyDown(Keys.One, () => {
mw.Event.dispatchToServer("PrintPlayersInfo");
});
}
}
}
getControllerRotation
• Static
getControllerRotation(outer?
): Rotation
other
Obtain the rotation of the controller
Parameters
outer? Rotation | Usage: variable receiving rotation default: undefined |
---|
Returns
Rotation | The rotation input of the current controller |
---|
Precautions
If the outer is not empty, return the outer. Otherwise, return a new Vector object. It is recommended to pass in the outer to reduce the new object and the outer cannot be null/undefined
Usage example: create a script named "Example_Player_GetControllerRotation", place it in the object bar, open the script, enter the following code to save, run the game, you will get the rotation input by the current controller and overlay the step size to overwrite, press the keyboard "1" to start or stop overwriting the rotation of the controller. See the effect of camera rotating around character in the scene. The code is as follows:
@Component
export default class Example_Player_GetControllerRotation extends Script {
// Declare variables
flag: boolean;
rot: Rotation;
stride: Rotation;
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
this.flag = false;
this.rot = Rotation.zero;
this.stride = new Rotation(0, 0, 1);
// Activate the cyclic periodic function
this.useUpdate = true;
// Add a key method: Press the keyboard "1" to send an event to the server to create a role and control it
InputUtil.onKeyDown(Keys.One, () => {
this.flag = !this.flag;
});
}
}
// The periodic function is executed on a frame by frame basis. To execute this function, the value of this.useUpdate needs to be set to true, where dt is the delay (in seconds) between the current frame and the previous frame
protected onUpdate(dt: number): void {
if(SystemUtil.isClient() && this.flag) {
// Obtain the rotation of the current controller input and overlay the step size for coverage
Player.getControllerRotation(this.rot);
Player.setControllerRotation(this.rot.add(this.stride));
}
}
}
@Component
export default class Example_Player_GetControllerRotation extends Script {
// Declare variables
flag: boolean;
rot: Rotation;
stride: Rotation;
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
this.flag = false;
this.rot = Rotation.zero;
this.stride = new Rotation(0, 0, 1);
// Activate the cyclic periodic function
this.useUpdate = true;
// Add a key method: Press the keyboard "1" to send an event to the server to create a role and control it
InputUtil.onKeyDown(Keys.One, () => {
this.flag = !this.flag;
});
}
}
// The periodic function is executed on a frame by frame basis. To execute this function, the value of this.useUpdate needs to be set to true, where dt is the delay (in seconds) between the current frame and the previous frame
protected onUpdate(dt: number): void {
if(SystemUtil.isClient() && this.flag) {
// Obtain the rotation of the current controller input and overlay the step size for coverage
Player.getControllerRotation(this.rot);
Player.setControllerRotation(this.rot.add(this.stride));
}
}
}
getPlayer
• Static
getPlayer(uniqueId
): Player
other
Get the Player and find the corresponding Player according to the userId
Parameters
uniqueId string number | Usage: user ID or Player Player ID |
---|
Returns
Player | Player Object |
---|
Precautions
Get Player according to ID. The ID can be playerId or userId.
Usage example: create a script named "Example_Player", place it in the object bar, open the script, enter the following code to save, run the game, and you will get the Player through the getPlayer API. Press the keyboard "1", use the getPlayer function to obtain the Player object through userId or playerId, print the name, and see the effect of getPlayer in the console. The code is as follows:
@Component
export default class Example_Player extends Script {
protected onStart(): void {
Player.getPlayer(Player.localPlayer.playerId);
}
}
@Component
export default class Example_Player extends Script {
protected onStart(): void {
Player.getPlayer(Player.localPlayer.playerId);
}
}
setControllerRotation
• Static
setControllerRotation(newRotation
): void
other
Overtrite the rotation of the controller
Parameters
newRotation Rotation | Usage: New rotation value |
---|
Usage example: create a script named "Example_Player_SetControllerRotation", place it in the object bar, open the script, enter the following code to save, run the game, you will get the rotation input by the current controller and overlay the step size to overwrite, press the keyboard "1" to start or stop overwriting the rotation of the controller. See the effect of camera rotating around character in the scene. The code is as follows:
@Component
export default class Example_Player_SetControllerRotation extends Script {
// Declare variables
flag: boolean;
rot: Rotation;
stride: Rotation;
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
this.flag = false;
this.rot = Rotation.zero;
this.stride = new Rotation(0, 0, 1);
// Activate the cyclic periodic function
this.useUpdate = true;
// Add a key method: Press the keyboard "1" to send an event to the server to create a role and control it
InputUtil.onKeyDown(Keys.One, () => {
this.flag = !this.flag;
});
}
}
// The periodic function is executed on a frame by frame basis. To execute this function, the value of this.useUpdate needs to be set to true, where dt is the delay (in seconds) between the current frame and the previous frame
protected onUpdate(dt: number): void {
if(SystemUtil.isClient() && this.flag) {
// Obtain the rotation of the current controller input and overlay the step size for coverage
Player.getControllerRotation(this.rot);
Player.setControllerRotation(this.rot.add(this.stride));
}
}
}
@Component
export default class Example_Player_SetControllerRotation extends Script {
// Declare variables
flag: boolean;
rot: Rotation;
stride: Rotation;
// When the script is instantiated, this function will be called before the first frame update/
protected onStart(): void {
// The following code is only executed on the client side
if(SystemUtil.isClient()) {
this.flag = false;
this.rot = Rotation.zero;
this.stride = new Rotation(0, 0, 1);
// Activate the cyclic periodic function
this.useUpdate = true;
// Add a key method: Press the keyboard "1" to send an event to the server to create a role and control it
InputUtil.onKeyDown(Keys.One, () => {
this.flag = !this.flag;
});
}
}
// The periodic function is executed on a frame by frame basis. To execute this function, the value of this.useUpdate needs to be set to true, where dt is the delay (in seconds) between the current frame and the previous frame
protected onUpdate(dt: number): void {
if(SystemUtil.isClient() && this.flag) {
// Obtain the rotation of the current controller input and overlay the step size for coverage
Player.getControllerRotation(this.rot);
Player.setControllerRotation(this.rot.add(this.stride));
}
}
}