Convert javaScript object to another type of object

This is due to Three.js + Socket IO + CANNON.js. I have a CANNON.RigidBody object on my SERVER server, which I cannot send as it is. Therefore, I will transform it like this:

// Create a sphere var mass = 5, radius = 1.8; var sphereShape = new CANNON.Sphere(radius); var physicsMaterial = new CANNON.Material("slipperyMaterial"); var sphereBody = new CANNON.RigidBody(mass, sphereShape, physicsMaterial); sphereBody.position.set(0, 10, 0); sphereBody.linearDamping = 0.9; cannonWorld.add(sphereBody); cannonEntities[(numBodies++).toString()] = sphereBody; player = { type: "player", data: { id:((numBodies++).toString()), position: sphereBody.position, quaternion: sphereBody.quaternion, velocity: sphereBody.velocity, radius:radius, mass:mass } } 

and sent it to my client ....

 broadcastJsonEvent(JSON.stringify(player)) 

In my CLIENT, I pass this player object to my control. Usually, instead of a player, you can pass a CANNON.RigidBody object.

 controls = new PointerLockControls(camera, player); scene.add(controls.getObject()); 

Since I cannot send the complete object, which is ... CANNON.RigidBody, I send it as a player object, and in PointerLockControls the last line looks like this ... And here everything fails.

 cannonBody.position.copy(yawObject.position); 

Now my player object does not have a copy method. What can I do? Please help. This is what I tried. Remember cannonBody = player !! And even if I get the copy method still does not work.

 var copyBody = new CANNON.Vec3(cannonBody.position.x,cannonBody.position.y,cannonBody.position.z); cannonBody = $.extend(cannonBody,new CANNON.RigidBody(cannonBody.mass,new CANNON.Sphere(1.8),new CANNON.Material("slipperyMaterial"))); cannonBody.position = $.extend(copyBody); cannonBody.position.copy(yawObject.position); 

And even if I get the copy method still does not work. :(

+4
source share
1 answer

Assuming you need to perform a copy operation, you can do this:

 CANNON.Vec3.prototype.copy.call(cannonBody.position,yawObject.position); 

This line of code uses the copy method from CANNON.Vec3 . You can look at Function.prototype.call to understand how this works. Please note that you need to download Cannon.js on the client to do this.

Depending on what the rest of your code does, it may be convenient for you to create a local CANNON.RigidBody instance on the client. You can update this body with new conditions when you receive updates from the server.

0
source

Source: https://habr.com/ru/post/1482461/


All Articles