Create plugin to track character movements in real time

Hi!

I'm pretty new to RPG Maker MZ plugin development.

I'm developing a game and I would like to track character movements in order to send the position to a WebSocket server to allow multiplayer game.

But I don't know how to create a plugin where I can track the position of the main character. Is there any documentation or do you have any sample to see how to implement it?

Thanks!

I've moved this thread to Plugin Requests. Thank you.

Hi there!

I don't know anything about multiplayer games. So I don't know if it needs to be more complex than that, but to get the main character's position:

$gamePlayer.x - coordinate X
$gamePlayer.y - coordinate Y

You can send that info to your server?
Multiplayer requires much more than tracking the player position.
Tracking the player position will allow you to display the coordinates somewhere on the website, but nothing more.

allowing player interaction for example requires a rewrite of almost the entire engine because the engine has nothing to keep track of multiple player in one map, they would ignore each other.
I've started with this code to get player position changes:

Code:
(() => {
    const pluginName = "EMR_SendPosition";
    let textPictureText = "";

    PluginManager.registerCommand(pluginName, "set", args => {
        textPictureText = String(args.text);
    });

  let mapId = 0;
  let positionX = 0;
  let positionY = 0;

  var Scene_Map_Create = Scene_Map.prototype.create;
  Scene_Map.prototype.create = function() {
    Scene_Map_Create.call(this);
    console.log($gameActors)
    mapId = $gameMap.mapId();
    positionX = $gamePlayer.x;
    positionY = $gamePlayer.y;
  };

  var Scene_Map_Update = Scene_Map.prototype.update;
  Scene_Map.prototype.update = function() {
    Scene_Map_Update.call(this);
    managePlayerMovement();
    //var playerTemplate = $gameMap._events[1];
    // THIS IS THE IMPORTANT LINE, of course you have to put real coordinates instead of x & y
    //playerTemplate.moveStraight( playerTemplate.findDirectionTo(4, 7) );
   
  };

  var managePlayerMovement = function() {

    let newPosition = [$gameMap.mapId(), $gamePlayer.x, $gamePlayer.y]
    let lastPosition = [mapId, positionX, positionY]

    if (!newPosition.equals(lastPosition)) {
        mapId = $gameMap.mapId();
        positionX = $gamePlayer.x;
        positionY = $gamePlayer.y;
        console.log(`${mapId} ${positionX} ${positionY}`)
    }

    // $gamePlayer.refresh();
  }
})();

I'm also developing a Websockets server and client to manage messages between games. I will share it when I finish a first alpha version.
Real time tracking of player position is done by:
Const trackX = $gameplayer._realX
Const trackY = $gameplayer._realY

To make a multiplayer tracking system, it would be best to use the normal x and y values rather than realX and realY.

To create an instance of tracking multiple players with collision, you need the web client to continuously GET that data and update it in an invalid coordinates array.

To display multiplayer characters, you need to create an object array of old and updated positions, the old and updated player data, placeholder player data and then have it update on your end using that data received from server/client talk.

There may be issues with latency using the above method in which storing a 'path' if accurate movement replication is not necessary would be best. If accurate move path is required, well, that's another story. One that includes tales of optimization, lag and a whole lot of issues from multiplayer games with large amount of players.
Real time tracking of player position is done by:
Const trackX = $gameplayer._realX
Const trackY = $gameplayer._realY

To make a multiplayer tracking system, it would be best to use the normal x and y values rather than realX and realY.

To create an instance of tracking multiple players with collision, you need the web client to continuously GET that data and update it in an invalid coordinates array.

To display multiplayer characters, you need to create an object array of old and updated positions, the old and updated player data, placeholder player data and then have it update on your end using that data received from server/client talk.

There may be issues with latency using the above method in which storing a 'path' if accurate movement replication is not necessary would be best. If accurate move path is required, well, that's another story. One that includes tales of optimization, lag and a whole lot of issues from multiplayer games with large amount of players.
I'm implementing WebSockets.

I have modify my method managePlayerMovement:
Code:
var managePlayerMovement = function() {
        let newPosition = [$gameMap.mapId(), $gamePlayer.x, $gamePlayer.y]
        let lastPosition = [mapId, positionX, positionY]

        if (!newPosition.equals(lastPosition)) {
            mapId = $gameMap.mapId();
            positionX = $gamePlayer.x;
            positionY = $gamePlayer.y;
            if (!ws) {
                showMessage('No WebSocket connection');
                return;
            }
            
            let item = {type: 'movement', player: playerId, position: newPosition, lastPosition: lastPosition}
            ws.send(JSON.stringify(item));
        }

    }

And I'm receiving the other players movements with this one:
Code:
var initConnection = function () {
        if (ws) {
            ws.onerror = ws.onopen = ws.onclose = null;
            ws.close();
        }

        ws = new WebSocket(`ws://localhost:8080`);
        ws.onerror = function () {
            showMessage('WebSocket error');
        };
        ws.onopen = function () {
            showMessage('WebSocket connection established');
        };
        ws.onclose = function () {
            showMessage('WebSocket connection closed');
            ws = null;
        };
        ws.onmessage = function (message) {
            const parsedMessage = JSON.parse(message.data)
            showMessage(parsedMessage.position);
            players.set(parsedMessage.player, parsedMessage.position);
            players.forEach((position, name) => {
                console.log(`${name} + ${position}`)
                if (position[0] === mapId & name !== playerId) {
                    movePlayer(position[1], position[2]);
                }
            })
        }
    };

    const movePlayer = function (x, y) {
        console.log(`${x} ${y}`);
        if( $gameMap.events().length > 1) {
            var playerTemplate = $gameMap._events[1];
            playerTemplate.moveStraight(playerTemplate.findDirectionTo(x, y));
        }
    }

My new problem is that the playerTemplate.moveStraight(playerTemplate.findDirectionTo(x, y)) action is only done when I move my character.

Is there any way to force Scene update in order I can force the other players' movements when I receive a message through Websockets?
I'm implementing WebSockets.

I have modify my method managePlayerMovement:
Code:
var managePlayerMovement = function() {
        let newPosition = [$gameMap.mapId(), $gamePlayer.x, $gamePlayer.y]
        let lastPosition = [mapId, positionX, positionY]

        if (!newPosition.equals(lastPosition)) {
            mapId = $gameMap.mapId();
            positionX = $gamePlayer.x;
            positionY = $gamePlayer.y;
            if (!ws) {
                showMessage('No WebSocket connection');
                return;
            }
           
            let item = {type: 'movement', player: playerId, position: newPosition, lastPosition: lastPosition}
            ws.send(JSON.stringify(item));
        }

    }

And I'm receiving the other players movements with this one:
Code:
var initConnection = function () {
        if (ws) {
            ws.onerror = ws.onopen = ws.onclose = null;
            ws.close();
        }

        ws = new WebSocket(`ws://localhost:8080`);
        ws.onerror = function () {
            showMessage('WebSocket error');
        };
        ws.onopen = function () {
            showMessage('WebSocket connection established');
        };
        ws.onclose = function () {
            showMessage('WebSocket connection closed');
            ws = null;
        };
        ws.onmessage = function (message) {
            const parsedMessage = JSON.parse(message.data)
            showMessage(parsedMessage.position);
            players.set(parsedMessage.player, parsedMessage.position);
            players.forEach((position, name) => {
                console.log(`${name} + ${position}`)
                if (position[0] === mapId & name !== playerId) {
                    movePlayer(position[1], position[2]);
                }
            })
        }
    };

    const movePlayer = function (x, y) {
        console.log(`${x} ${y}`);
        if( $gameMap.events().length > 1) {
            var playerTemplate = $gameMap._events[1];
            playerTemplate.moveStraight(playerTemplate.findDirectionTo(x, y));
        }
    }

My new problem is that the playerTemplate.moveStraight(playerTemplate.findDirectionTo(x, y)) action is only done when I move my character.

Is there any way to force Scene update in order I can force the other players' movements when I receive a message through Websockets?
You can pull the character data from scene spriteset._characterSprites

Ah, I forgot you'd need to update each map on the server in its own instance.

Honestly (ノ•̀ o •́ )ノ ~ ┻━┻

That's a lot of work.
You can pull the character data from scene spriteset._characterSprites

Ah, I forgot you'd need to update each map on the server in its own instance.

Honestly (ノ•̀ o •́ )ノ ~ ┻━┻

That's a lot of work.

I have a lot of time! Hehehe, yes I know, it is a hard task.

Let me share it my current solution:

Websockets on message event:
1. Receive player position and update it
2. If player is on your map, update character position
3. Force Game Map Update to move character

Code:
ws.onmessage = function (message) {
            const parsedMessage = JSON.parse(message.data)
            showMessage(parsedMessage.position);
            players.set(parsedMessage.player, parsedMessage.position)
            players.forEach((position, name) => {
                if (position[0] === mapId & name !== playerId) {
                    console.log(`${name} + ${position}`) // TBD check last position
                    movePlayer(position[1], position[2]);
                    $gameMap.update()
                }
            })
        }

Move character:
I have created a fix event (event 1) with a character (so this code is only compatible for 2 players in the same map)
1. Check that this events exists on the map
2. Update the position with moveStraight and findDirectionTo
Code:
const movePlayer = function (x, y) {
        if( $gameMap.events().length > 1) {
            var playerTemplate = $gameMap._events[1];
            playerTemplate.moveStraight(playerTemplate.findDirectionTo(x, y))
        }
    }

What's the difference between that code with using your alternative "pull the character data from scene spriteset._characterSprites"?

I was not able to do it 🙁

Original thread: https://forums.rpgmakerweb.com/threads/create-plugin-to-track-character-movements-in-real-time.148628/