@tiki720/

Multiplayer 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
90
91
92
93
94
95
96
97
98
// 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 * 0.1,data.y * 0.1)
		}
	})
	socket.on('createBullet', (data)=>{
		var i = players.findIndex((p) => p.id == data.id)
		if (i >= 0) {
			var me = players[i]
			var b = new bullet(new vector(me.pos.x,me.pos.y),Math.PI * 2 * Math.random(),2)
			bullets.push(b)
			console.log(b)
		}
	})
})
players = []
bullets = []
const frameRate = 1000 / 60
function loop() {
	for (let i = 0; i < players.length; i++) {
		players[i].run()
	}
	for (let i = 0; i < bullets.length; i++) {
		bullets[i].run()
	}
	io.sockets.emit('setPlayers', players)
	io.sockets.emit('setBullets', bullets)
	setTimeout(loop, frameRate)
}
loop()
function player(id) {
	this.pos = new vector(0, 0)
	this.vel = new vector(0, 0)
	this.acc = new vector(0, 0)

	this.dir = new vector(0, 0)
	this.moving = false

	this.id = id

	this.run = function() {
		this.pos.add(this.vel)
		this.vel.add(this.acc)
		this.vel.mult(new vector(0.99, 0.99))
		this.acc.mult(new vector(0, 0))
		if (this.moving) {
			this.addAcc(this.dir)
		}
	}
	this.addAcc = function(vector) {
		this.acc.add(vector)
	}
}
function bullet(pos,angle,speed){
	this.pos = pos
	this.vel = new vector(0, 0)
	this.acc = new vector(Math.cos(angle) * speed, Math.sin(angle) * speed)

	this.run = function(){
		this.pos.add(this.vel)
		this.vel.add(this.acc)
		this.vel.mult(new vector(0.99, 0.99))
		this.acc.mult(new vector(0, 0))
	}
}
function vector(x, y) {
	this.x = x
	this.y = y
	this.add = function(vector) {
		this.x += vector.x
		this.y += vector.y
	}
	this.mult = function(vector) {
		this.x *= vector.x
		this.y *= vector.y
	}
}
node v10.16.0