Build a multiplayer game with React Three Fiber and Socket.io

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
let's build the multiplayer seems like experience with the reactive fiber and socket.io [Music] hi let's discover how to enable websocket into our 3js project in this first episode we will learn how to communicate between a server and multiple clients by creating a simple character movement in the next episodes we will add items to our scene and interact with as well as a character customizer let me know in the comments what you like to see in this project as usual let's start by getting the starter pack repository on my GitHub account code copy then in a terminal git clone the repository address and I will name the folder direction to client because we will create a server folder after now we can go into it see the clients yarn and yarn Dev let's try to open the URL now you should see this Cube and be able to rotate around we'll be using the 3D model from quaternius in polypiza animated woman you can hit download and download glb in your project go to clients public create a new folder name it models then drag and drop your model into now we can run npx gltf jsx public models animated woman then Dash o to say the output file so Source components and animated woman we will keep the name of the model and dash R public to say the root directory where our files are located hit enter we can restart our server and look at what it did it generated a new component named animated woman with everything that the model contains it will be easy for us to use it by default it name it model but I prefer to name it directly animated woman and we are ready to use it let's go to experience let's replace our Cube with The Animated woman let's import it and use it if we look at what we have we have many issues the camera position is wrong and we have no light so it appears black for the lights we can use the environment component from dry with the preset Sunset and also add an ambient light for more more lights with a low intensity for the camera position we go into up and on the camera settings here we can put eight eight and eight now we have a view closer to what the seams are let's animate the animated woman as it comes with animation let's look at what animation we have by doing a console log actions now in the console we can see an object with all the different animations so it starts with character Armature we have idle and we have walk we'll be using those two ones and the use animation we can remove our log and Define a state with animation and set animation to set our animation value so by default we will put in the idle one now we need to play our animation inside a user effect that will be triggered when the animation change so here we set animation in the array we will do actions of animation dot reset then we fade in and we play it and what we will return is the function to stop the current animation so action of animation and Fade Out now we can see on our character that it is Idle it's not very visible let's try another one let's change it to run now we can see our character is running okay let's undo it and set idle then we will Define the props that are available on our woman we don't want to have it this way we will use an object and the structure rate props and add other properties here let's say we want to change the color of the hair hair color is equal to Green then the top color will be a pink and bottom color will be brown the reason I'm doing this for the props is because now I can set default value so I don't need to Define them in the experience but also if I do control space my code editor know that there are those props available even if we are not using typescript now let's apply those colors on the material we have hair blonde so here we need to set the hair color let's create a mesh tender material with a color equal to the hair color and close skinned mesh then maybe it was over body it's white and skin okay this one is for the top so we'll use another material with top color and the legs here so it's at the bottom the pins and bottom color okay now our character correctly had the colors we set let's try to add another character next to it it's what we really want to do online we go back to experience add another animated woman set the position X to 1. and let's change the hair color let's say red top color to Blue okay so we have two weird things happening those artifacts but also our character has disappeared from here the thing is when we are using skin mesh by default it's reusing it instead of duplicating it so we need to clone it to half both available at the same time let me tell you how I discovered it I had an issue as soon as I was using multiple skin mesh so I looked into the Discord of Joy library and so people speaking about it and I saw this example that show how to do it by cloning the mesh using skeletal new tears and use graph we will exactly use the same here let's go to animated woman here they are not using those nodes they are using scene instead then we can paste what we did it's a use memo it's cloning the scene and then it's creating the nodes with use graph but we don't have a skeleton utils it's from another Library we need to add yarn add 3 STD lib okay restart the development server and now we can import skeleton utils now no more artifacts and we have our two characters visible on screen we can create more just for making it look a bit better not excellent but better let's add some contact Shadows with a blur of two now we can see they are on the floor now time to add the networking part with socket.io you can go to the documentation and read a bit about it if you want to go further than this tutorial but what it does basically is enabling a fast connection using websockets between a server and multiple clients let's create our server code so it will be in a separate folder than the client one go to the root directory of your project create a folder named server and go to it maybe we can have one terminal in the client and another one in the server we will add socket IO Library yarn add socket dot IO it will automatically generate a package.json file server okay so it has socket.io the code of our server we want to make it in index.js what we need to do is we import server from socket.io then we will create IO it will be a server so server to be able to use it with localhost we will need to add cores we just need to set the origin to be the client origin so it's localhost and the port so I think it's 5173 to be sure you can look at the client around yarn Dev and here you can see the URL and then you will do io.listen and you set a port either 3000 but I often use it for another project I'm working on so I will set 30 000 one okay now we have our server we can say on connection event we will have a socket it's between us the server and a client we can close it and inside we will add some listener to what is happening when we are inside those brackets it means someone connected user connected then we can add events on what is happening the first one we want to do is Socket dot on and disconnect we would just say user disconnected we will also do something else it will be socket.mit to send a message to this socket so it will be only the client that connected we would just say hello we can add parameters here and as many as we want but we won't okay now we want to run our server to see if we did everything correctly so we will need to add um yarn add D uppercase D and another mode so every time we will save it will restart the server now in our package.json of the server we will add scripts we will say Dev it will be nodemon of index.js and because we are using some imports we need to say that type is module okay now let's try yarn Dev and it says it's touching the server we will see if it works now let's go back to the client we will need to add socket dot IO Dash client okay we can restart our server and hide the terminal now let's go back to our client and we will create a new component named socketmanager.jsx I'm also experimenting so maybe it's not the best solution right now but maybe I will change it in the future we will see so we'll have export const socket manager and on top of it we will create our socket so it will be export const socket is equal to IO so IO should be from socket IO client and we need to pass the URL here so it's localhost and 3001. now in our socket manager we will use a use effects and we will play with our socket to monitor events we can create a function on connect we'll say connected also on disconnect Ed and also on the server what did we say index a hello event so we will add a listener for hello function on hello console log hello okay now we will do socket dot on connect and we will bind each event to the right function let's connect down hello and now we can return a function that will unbind all those events so socket.off the name and the function we save we go to the app directly let's add it next to our canvas socket manager if we reload here we can see connected and hello and you can see user connected and disconnected multiple times because I did it multiple times so far we have the connection between the client and the server but now we need to add some logic to integrate those network with our UI let's go to our server here and we will create const characters it will be an array of character every time someone will log in we will add it to characters of course it's a very simple example you might need to create a rooms and do more stuff but here we want to go straight forward let's go to connection it's when someone joined the server what we want to do is to push into character the new user that joined ID it will be the socket ID so we know who it is then we will add some information for example the position and we will call a function to generate a random position we will create it just after we will also Generate random hair color and clothes to hair it will be hair color Generate random hex color same for top and bottom now we can go over it const Generate random position it will return I want an array not an object it will be math dot random multiply by three make it small the y-axis we want to set to zero and on the z-axis also three okay now Generate random hex color it does something I would never be able to write myself and okay now what it does it it generated the new character into the characters array but we need to notify everyone that there is this new character the socket I will explain how it works you can broadcast events to all connected clients it's what we want to do so it's on iO dot Emit and then your parameters but you can also send an event to everyone accepted the one that logged in to do so you use socket.broadcast instead of io.mit and else what we did previously is socket.mit so socket.mit is only to the socket connection so this client what we need to do is IO dot emit we'll say characters and send the characters array as it's pretty simple let's also add the on disconnect it will be character dot splice we find the index of the character and then we remove it once we removed it we need to notify everyone that is remaining on the server that there is a new list so we emit the new list of characters let's see if we didn't break everything go to socket manager we add a new function on characters and we will log the characters so on characters let's let's name it value we will use a state later for characters so it will be a value socket on characters and don't forget to unbind it after now if we reload we have the connected hello and characters we can see it's an array containing currently only one we see two because it's manually failure we have the color the ID and the position let's try to add another tab when I open this tab we have a new event on the first one with the new list of character there are the two ones you can see I made something agnostic I don't know me as a user what character am I but I don't care currently maybe later I will need to know now that we have our characters List let's try to display them on screen to have a simple State management system I will add the jotai library oh sorry it's not the server it's the client yarn add jotai I can restart the dev server and hide it I will create here the characters atom that will be an array so it will be like a State Global State available everywhere now in socket manager we can do characters and set character will be used atom of characters data we won't use characters so we can remove it we also need to import it I don't know why the auto completion doesn't work so use atom and atom and now inside our events we will say set characters to Value we now have inside the characters here the state the characters from the server now we can go to our experience use the atom also here so it will be a const characters is equal to use atom of characters atom we need to import it because it's in socket manager and instead of having it here and this way we will do a characters dot map and for every character we will render an animated woman the key will be character.id for the position we will say character dot position and also hair color which will be character dot hair color same for top and same for bottom okay now we need to add the parentheses here and to remove the two existing animated woman if I have one tab I see this character here if I open another tab we can see we have two characters if I reload I have an issue but it looks it's based on the animation so let's fix it go to animated woman it's when we fade it out sometimes we have no more the actions so we can add a question mark here now if we look we can reload it will generate a new character at a new random position and on both green we will have the correct values let's try to add another tab maybe here and now we have a three character of course we can add more and more and when we remove a tab the character disappears we are almost good let's add that when we click on somewhere our character moves toward that direction in our experience let's add a floor it will be a plain geometry the size will be 10 by 10 and we will add a mesh standard material that we will say to if 0 if 0 f 0 so it's a light gray we also need to rotate it over the x-axis and to position it a bit below the contact Shadow so position y will be minus zero zero one rotation here okay we now have a floor we want that when we click somewhere we will send an event to say I want to move to that position we can do it simply on click we'll have an event we will do socket dot emit we will call the function move and the parameters we will do e dot Point dot X we want to stay at zero every time so we keep zero and E dot Point dot Z we can also add some events on the mesh to know that we can click that we are hovering it and that it is clickable let's add on pointer enter set on floor true and on pointer leave set on floor false let's add this state we need to import it and we will use use cursor to say okay we are hovering it now when we are hovering the floor we can see we have a pointer when it's out our pointer is normal and when we click nothing happened because we need to handle those events go back to the server here and we will add a new event socket dot on move we now have the position parameter here and we will need to add our logic we need to find our character with characters DOT fine based on the ID socket ID then we update the character position and we emit the new list of updated characters position it's not the cleanest way to do it because we are sending all the characters at once for just a small event but it's what we are going to do for Simplicity purpose now if we try it when we click our character move to where we click currently it's teleporting to the position but we can update it to make a work animation towards the duration first thing to make our life easier is to go back to experience and instead of using character.position which is an array we will transform it to a three Vector 3 dot Vector 3 of character position zero also and two okay we can use the position one but it will always be zero two okay we also need to import three Imports three at three so it will be easier for us to already have a vector R3 now in our animated woman we will change the way our position work so we will go maybe on top here with a const position is equal to use memo and it will be props dot position and we want it to happen just the first time we init it we want to have the initial position so it will be this position and instead of applying it from here the props we will override it here by doing position is equal to position now when we click our character doesn't move we need to add that logic to go to that new position we can do a use frame then we will check if our current position of the group so the reference of the object dot distance to to the props position which is updated by the network is over uh 0.1 if it's true we don't want to learn because it will smooth the animation we want it to be linear and straightforward we will create a direction vector by using our current position that we will clone and we will subtract the real position we want to go to we will normalize it to have a direction and we will multiply as color by a speed so it will be our movement speed let's define the movement speed here for example let's put 0.032 now we have our direction we can go towards the direction by using sub on our current position if we look at the result when we click the sliding on the floor but it's very linear and at the same Pace to make it better we can say group dot current dot look at and add the position we Target now when we click they are facing the directions they are going to and to make it realistic we will just do set animation we will make run and if we are not moving we will set it back to idle now we click and our character are moving but maybe it's a bit slow in the transition instead of half a second let's say the fade 20 to 32. let's try now it starts faster and it stops faster so it's more realistic thank you for watching I hope you enjoyed this video if it's the case please hit the like button as it really helps the channel grows and be more visible to our creative developer Community don't forget to subscribe to not miss the next episodes in the meantime if you want to continue learning you can watch this video tutorial on here
Info
Channel: Wawa Sensei
Views: 13,374
Rating: undefined out of 5
Keywords: threejs, three js tutorial, threejs tutorial, react three fiber, react three fiber tutorial, three js react, r3f tutorial, three js, three.js, pmndrs drei, pmndrs, webgl tutorial, react, threejs journey, threejs course, socket io react, socketio, three js multiplayer game, react three fiber metaverse, react three fiber multiplayer, three js socket io, react three fiber socket io, how to build a 3D multiplayer game
Id: uLv1Zu8GyUw
Channel Id: undefined
Length: 24min 42sec (1482 seconds)
Published: Fri Aug 04 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.