Sign In Register

How can we help you today?

Start a new topic

Making a simple thing like Global Chat....

Hello, I'm making a Global Chat and as the support suggested in other topic, trying to make a runtime collection of online players and sending the chat message to every one of them.


I have this cloud code attached to GS_PLAYER_CONNECT

var json = {"pid":Spark.getPlayer().getPlayerId()};
var collection = Spark.runtimeCollection("online");
collection.save(json);


and this to GS_PLAYER_DISCONNECT

var collection = Spark.runtimeCollection("online");
collection.remove({"pid": Spark.getPlayer().getPlayerId()});


Testing on Test Harness it looks like it's working but does this code guarantee the list doesn't get messed up?


And sending the same chat message to every player, is it really a good thing to do?


I mean.., isn't it better to create a runtime collection that stores chat messages and let players retrieves messages if there're new messages? To do that performantly, you would need to store chat index to somewhere outside database and I thought I could use property to store the index but it seems properties can't be modified programmatically.



Well sorry, forget about the "good thing to do?" lines and below. Maybe I'm being a paranoid.
And collection.save(json); should be collection.insert(json);

 

ok.. the code on GS_PLAYER_CONNECT is now this

var pid = Spark.getPlayer().getPlayerId();
var json = {"pid":pid};
var collection = Spark.runtimeCollection("online");
collection.update(json,json,true,false);



1 person likes this
And the cloud code on my chat event.

var chatString = Spark.getData().Text;
var dName = Spark.getPlayer().getDisplayName();
var json = {"displayName":dName, "Message":chatString};
var msg = Spark.message(null);
var collection = Spark.runtimeCollection("online");
var ids = collection.distinct("pid")
msg.setPlayerIds(ids);
msg.setMessageData(json);
msg.send();

Hope this saves someones's headache.


1 person likes this

Everyone googling how to do global chat, this is it.

I have tried the other crazy batch job systems and making this weird global team system that many people have cobbled together.


This is the best solution. I have no idea why global message isn't a default function but that's ok.


Thank you so much elin cat

Login to post a comment