Supporting multiplayer
In this tutorial, I have deliberately made some pit-falls that I have seen new developers falling in which prevents multiplayer gameplay from working.
So let's clean up in this mess, the first thing we want to address is the $CoinsFound
global variable. We set it in the callback in data/CoinCollection/server/coin.tscript
so how can we just use it directly in data/CoinCollection/client/commands.tscript
? When we play in single-player mode the player and the host is the same process, this means we can use the global variable $CoinsFound
in both client and server simultaneous. However this is an anti-pattern because this won't work for other clients in a multi-player scenario.
We can fix this using dynamic variables. TorqueScript has something called dynamic variables which is a very simple but very smart concept. Basically you can define any variable on any object by assigning it a value.
We can use this to keep track on how many coins each client has picked up!
Remove the $CoinsFound
global, and change the onCollision
callback by adding %col.client.coinsFound++;
instead in data/CoinCollection/server/coin.tscript
so it looks like this:
However, there is still an issue here. We are currently showing the player that picks up the last coin that they won. We should show the one with most coins that they won and all others should be told they've lost. We can solve that by looping over the ClientGroup
SimGroup. The ClientGroup is a collection of all the clients who have joined the game.
So change the onCollision
callback to the following:
Now the last thing we need to do is to change the data/CoinCollection/client/commands.tscript
file, first of all we want to add a %score
parameter to the clientCmdShowVictory
function:
And then we need to add another function for when we lose:
Now your first multiplayer game should actually be working! Try opening two instances of Torque, in one of the instances you press “play” then you tick the “host” check box to the left of the Go
button. In the other instance you press join
, "Query LAN"
select the server that comes forth and join the game. Now you can compete with yourself about collecting most coins! Even better, you can host a LAN and let all your friends play your coin collection game with you! Give it a cool name and brag about it a little!
Last updated