javascript - variable is not getting defined even though the code works somwhere else -
so building game in 3 js , trying make multiplayer throught socket.io loading of characters array called players on server side
and pass each client when connect
socket.on('addplayer', function(username) { players.push(username) console.log(username + " joined") console.log("online users " + players) socket.broadcast.emit('syncplayers', players) socket.emit('syncplayers', players) })
and on client syncplayers looks
socket.on('syncplayers', function(players) { players.foreach(function(value) { if (value == username) { console.log("not adding " + value + " thats ") loadplayerdata(username) } else { console.log("player online " + value); newplayer = value; loadplayerdata(newplayer) addplayer(newplayer) } }); })
then calls wich sends server data
function loadplayerdata(playername) { console.log(playername) console.log("phase1") socket.emit('loadplayerdata', playername) }
then called , retrieved player name , data of players location problem lies
socket.on('loadplayerdata', function(data, username) { tomove = threeobjects[username + "char"] if (data == "null" || "") { console.log(username + " new") } else { console.log(username + " exists") console.log(tomove) tomove.position.set(world.spawnpointx, world.spawnpointy, world.spawnpointz) }
i keep getting uncaught typeerror: cannot read property 'position' of undefined
even though can use this
function addplayer(playername) { var charobjectname = playername + "char" var threeobject = models.tent1.mesh.clone(); scene.add(threeobject) //threeobject.position.set(world.spawnpointx, world.spawnpointy, world.spawnpointz) // set reference threeobjects[charobjectname] = threeobject; }
btw have object
var threeobjects = {};
can please explain why wont work , how fix it
you can read this answer understand difference between dot , brackets notation.
you getting error because, tomove
seems undefined , dot notation throw error if new user joins , if object empty.
check if helps. assign object key username , position value array this, {"usernamechar": {"position": [x,y,z]}}
socket.on('loadplayerdata', function(data, username) { if (data == "null" || "") { console.log(username + " new") } else { console.log(username + " exists") threeobjects[username + "char"]["position"] = [world.spawnpointx, world.spawnpointy, world.spawnpointz] } }
Comments
Post a Comment