CS2D Lua: Mouse Pointer Explosions

This tutorial will walk you through creating a simple CS2D script that creates explosions at the player’s cursor when they left-click. The script is not very useful in itself, but it will demonstrate how to query clients for data.

Our first order of business is to determine when a player left-clicks. Left-click is bound to attack in CS2D, so we’ll use the attack hook to catch all left mouse button clicks.

With a basic structure in place, we need to determine where a player’s cursor was when they left-clicked. This is achieved in two steps: we need to request data from the client, and then retrieve the data.

To request data from the client, we have to use the reqcld function. It needs the ID of the client we’re requesting the data from, which is provided to us by the attack hook firing, and the kind of data we need. Because we’ll be creating explosions on the map, we need the position of the player’s pointer on the map. This is governed by data type 2 (see reference). So, with this in mind, we need to update our function leftclick accordingly:

The next step is retrieving the data we requested. reqcld is asynchronous, which means that it requests the data, but doesn’t return it. If it did, the server would have to stop exchanging all data simply to wait for this piece of information – just imagine a server stopping every time someone left-clicked. Doesn’t sound nice, does it?

To prevent this, reqcld simply requests the data – that is the extent of its authority. The request is sent to the client, and the client sends the appropriate data – the absolute pointer position, in our case – to the server once it received it. The time it takes for a player to receive the request and send the data depends on the player’s ping.

Once the server receives the client’s data, it fires a clientdata event, passing the client ID, data type and the data itself as arguments to functions with that hook. So, now we know we need to make a function that will process the data received by the server and do what we want with it – namely, create an explosion at that position using the explosion console command:

This code will now work, and left-clicking anywhere on the map will create an explosion on that tile.

Now you should have an idea on how to request and handle client data in CS2D. More advanced constructions are left as an exercise for the reader for now, but if you have any questions – leave a comment.

Published by



Developer, human and programming language enthusiast, teacher at heart. Please remember: all my opinions are independent and subjective.

Leave a Reply

Your email address will not be published.