Sunday 19 March 2017

NodeJS + html5 canvas Player click to move

I currently have a NodeJS server setup that connects to my html5 canvas. The canvas displays the user as a number (given to them when they join) Not implemented a login yet. Now i am having a lot of trouble with the click to move event. As the numbers already appear on the canvas all i want do is have the canvas read where the click is on it and register it to the server allowing the player to move to that location. I can implement WASD but i want to use the click to move instead of WASD. All i can find over the internet is to display co-ordinates but not update the players location

[JavaScript]

   var express = require('express');
var app = express();
var serv = require('http').Server(app);

app.get('/',function(req, res) {
    res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));

//Port to listen for client
serv.listen(2000);
console.log("Server Started");

var SOCKET_LIST = {};
var PLAYER_LIST = {};

var Player = function(id){
    var self = {
    // Character Starting
        x:0,
        y:0,
        id:id,
        number:"" + Math.floor(10 * Math.random())

    }
    return self;
}

var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
    socket.id = Math.random();
    SOCKET_LIST[socket.id] = socket;

    var player = Player(socket.id);
    PLAYER_LIST[socket.id] = player;

    socket.on('disconnect',function(){
        delete PLAYER_LIST[socket.id];
    });
});

setInterval(function(){
    var pack = [];
    for(var i in PLAYER_LIST){
        var player = PLAYER_LIST[i];
        player.x++;
        player.y++;
        pack.push({
            x:player.x,
            y:player.y,
            number:player.number
        });    
    }
    for(var i in SOCKET_LIST){
        var socket = SOCKET_LIST[i];
        socket.emit('newPositions',pack);
    }



},1000/30);

[HTML]

<canvas id="ctx" width="1500" height="900" style="border:1px solid #000000;"></canvas>
</center>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
    var ctx = document.getElementById("ctx").getContext("2d");
    ctx.font = '30px Arial';

    var socket = io();

    socket.on('newPositions',function(data){
        ctx.clearRect(0,0,1500,900);
        for(var i = 0 ; i < data.length; i++)
            ctx.fillText(data[i].number,data[i].x,data[i].y);      
    }); 

</script>



via Jason Reynolds

No comments:

Post a Comment