@tiki720/

Multiplayer grid movement system

Nodejs

No description

fork
loading
Files
  • index.js
  • client
  • package-lock.json
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// File sharing to clients
const path = require('path')
var __dirname = path.resolve()
const express = require('express')
const app = express()
const serv = require('http').Server(app)
app.get('/', function(req, res) {
	res.sendFile(__dirname + '/client/index.html')
})
app.use('/client', express.static(__dirname + '/client'))
serv.listen(2946)
console.log('server started')

// Data sharing to clients
const io = require('socket.io')(serv, {})
io.sockets.on('connection', function(socket) {
	var p = new player(socket.id)
	players.push(p)
	socket.emit('newPlayer', socket.id)
	socket.on('playerMove', (data) => {
		var i = players.findIndex((p) => p.id == data.id)
		if (i >= 0) {
			players[i].moving = data.moving
			players[i].dir = new vector(data.x,data.y)
		}
	})
	socket.emit('setPlayers', players)
})
// Game stuff
players = []
function player(id) {
	this.pos = new vector(0, 0)
	this.des = new vector(0, 0)

	this.dir = 0
	this.moving = false

	this.id = id

	this.getDes = function() {
		if (this.moving) {
			this.des = new vector(
				this.pos.x + this.dir.x,
				this.pos.y + this.dir.y
			)
		}else{
			this.des = this.pos
		}
	}

	this.progress = 0

	this.run = function() {
		if (!this.pos.compare(this.des)) {
			if (this.progress >= 1) {
				this.progress = 0
				this.pos = this.des
				this.getDes()
				io.sockets.emit('setPlayer',this)
			} else {
				this.progress += 0.003 * frameRate
			}
		}else{
			this.getDes()
			io.sockets.emit('setPlayer',this)
		}
	}
}

function vector(x, y) {
	this.x = x
	this.y = y
	this.compare = function(vector) {
		return this.x == vector.x && this.y == vector.y
	}
	this.add = function(vector){
		this.x += vector.x
		this.y += vector.y
	}
}
const frameRate = 1000 / 60
function loop(){
	for (let i = 0; i < players.length; i ++){
		players[i].run()
		//console.log(players[i])
	}
	setTimeout(loop,frameRate)
}
loop()
node v10.16.0