How to get Mouse Position in 3D and 2D! (Unity Tutorial)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome i'm your code monkey in this quick video we're going to learn how to get the miles on position in both 2d and 3d this is really simple but they require different methods i receive a lot of comments from people asking why their code doesn't work and a lot of the times the issues that they're using the 2d method in a 3d game which really does not work so first let's see the 2d version which is super simple over here i have my demo scene all i have is this sprite and i want it to found the mouse the main camera over here is set up in 2d so the projection is orthographic it is placed on 0 0 and -10 on the zen so the center of the screen is on zero zero and over here on the size it's got an orthographic size of ten meaning that down here is on zero zero up here is on zero plus ten and down here on zero 0-10 okay so let's begin by making our script name this the mouse position 2d and here i'm going to attach it to my mouse target object okay so here let's do things step by step so let's make a simple update and on our update let's just do a debug.log on the mouse position and we're going to grab it through the input and grab the mouse position so let's see what this one returns and here with the game running we can see what's happening so you can see that it does not return the milestone position so down the center we do not get a zero zero instead if i go over here to the lower left corner that's where i get the zero zero and if i go on to the upper right corner it's at this value which is the width and height of this game window so if you look into the stats the game window has this screen size 1044 by 587 and if i put it right down the corner yep it's exactly that one so what we get from here is the screen position now we need to convert that screen position into a world position in order to do that we're going to need a reference to our camera so let's add it up here make it a serialized field so we can set it in the editor of the camera let's call it the main camera and here in the editor we see the film let's just drag the main camera all right so we have our camera reference now alternatively if you only use one camera you can directly use camera.main if you only have one camera then using this is perfectly fine i'm only using this method just so it's more adaptable so you can use it with any camera you want okay so with this we have our camera and now we can go into the camera and use the function screen to world point this one transforms a point from screen space into world space so in here we input input.mouseposition which as we saw was in screen space so if we now do a debug.log on this one and get rid of this one so if we do this let's see what it returns and yep now it does seem correct so if we put right down the center we do see a00 and up here we do see a zero plus 10 and down here a0 minus 10. now we also do see a slight issue on the zen so essentially the z that it's returning is the same set as on the main camera so here the main camera is on z of -10 whereas most of the world is probably going to be on a set of zero so here one simple thing is to make a vector three for the mouse world position and we grab it from this one then we take the mouse room position and set the z to zero and then let's just change this transform position to b and down so now it should follow the mouse and yep now everything is working perfectly so as i move the mouse the sprite is being placed exactly where it should be so i'm correctly getting the mouse wrong position in a 2d game so this is the method for doing it you take the main camera do a screen tour on point on the input mouse position and then if you want you zero out the z and then you have the mouse run position in a 2d game by the way if you find the video helpful please hit the like button it's a tiny thing but it really does help thanks alright so now on to the 3d method here is my demo 3d scene it's pretty much the same thing as before so i've got a main camera now it's set to perspective and then i've got a mouse target just with a nice visual and one extra thing is over here i've got a ground object and this one we can see in the scene view yep this is my ground object and the important thing is it does have a collider we're going to see why in a bit so now let's first actually try and see the error that so many people have so let's try using the 2d method in this scene and see what happens so on the mouse target if i just drag the mouse position 2d and drag the main camera reference let's see and yep the game is running but i am moving my mouse and there you go it does not change the position so this is the error that you see if you try to accumulate the miles wrong position using the 2d method on a 3d game this position that you're seeing here is actually the exact same thing as where the camera is so 9.1 13.1 15.6 yep exactly that so this is the mistake that many people make they use the 2d method on a 3d game which just returns the camera position the issue is that we cannot convert directly from a screen position into a world position in a 3d game if you think about it what you want is not a position based on the camera but rather the position in the world where the mouse is so what we need to do is essentially fire a laser from the camera pointing towards where the mouse is and then seeing where that position lets so that's exactly what we're going to do let's make a new sharp script let's name it our mouse position 3d and here on mouse target let's get rid of the 2d version and attach the 3d okay now here again first we're going to need a reference to our camera so let's do the exact same thing so reference to the camera now we set it here just drag it and now we do a predroid update and on the update we're still going to use the input.mouseposition except again as we saw this is a screen position so then we can use the function on the camera so main camera and now the function that we're going to use is the screen point to ring and we use our input mouse position as our parameter so this will return a ray from the camera towards where the mouse position is pointing so we grab this ray and then all we need to do is just cast it so we do a physics now raycast we pass in our ray and we've got an output of raycast hit now this one returns true if it hits something so if so let's do a transform.position and we're going to go inside our raycast hit and we grab the point which is the actual point where the ray hit the call either okay so that's it let's see and yep right away we can see that it does work so wherever i place the mouse you can see the little circle gets placed alongside the plane all right awesome however there's one potential issue here so i'm going to drag a building onto the scene okay so i added this building and now if i put the mouse over yep there you go as you can see the mouse is indeed interacting with the building so instead of placing the mouse on the floor it's placing it on top of the building now maybe this is what you want for example if you want to do some shooting then this would be correct however let's say that you are making a city building game or an rts and what you want is for the position to be on the ground and not collide with other objects so to solve that we can use layers if we select the ground object and over here on the layer let's add a new layer let's name it the ground then select the ground put it on that layer okay so far so good and now in our 3d class here let's expose another field and this one will be a layer mask and now back in the editor if we look at our script yep we've got a layer mask and now we can select something so for example let's select just the ground so back in the code here when we have our recast we can use the version that also takes in a layer mask there you go there's this one which takes a ray a rake has hit a float for the max distance and then the layer mask so if we wanted to go forever we can just use float max value and then for the layer mask we pass in our layer mask okay now let's see and right now it is correctly interacting with the floor and if i go towards the building if there you go now it goes through it and now it's interacting with the floor behind it so the mouse position is correctly ignoring the building and returns the position on the ground itself so this is perfect for any kind of city builder or rts where you want to ignore the actual physical objects on the scene alright so there it is this is how you get the mouse position in 3d you do a raycast from the camera towards the mouse and see where it hits so now you can refactor this code to make it super easy to use for example on the 2d version usually when i make a new project i always reuse my general utilities you can download them for free from mintycodemuck.com and in this class i have a very simple function to get the mouse around position and does exactly that goes into the world camera which by default uses the camera main and does the screen to run point on the input mouse position then i just got various versions in order to get it with the z or without the z these are set as static so i can call these functions from anywhere in my code very useful and for the 3d version i reuse this class it also has a static instance so that i can call it from anywhere and the function is exactly what we saw so it goes into the camera main the screen point array on the mouse position and just returns that point so for example if i want to add it to a new project i just make a new empty game object name it my mouse 3d then i add that script here on the script it has a mouse collider for the layer mask so in this case i would put it on the ground so just like that in 10 seconds i had the ability to get the mouse position in a 3d game and now anywhere in my code i can simply call upon this function and get the mouse world 3d position alright so there you have it that's how you get the mouse world position in both 3d and 2d they work differently so don't make the mistake of using the 2d method in a 3d game or vice versa do you prefer learning through a more guided path rather than separate tutorials then check out my complete step-by-step courses starting from scratch until the final polished games if you're into programming then get the awesome builder defender course learn how i make my own games using code build an awesome game that involves mechanics from city builders tower defense and survival games or if you're into visual scripting then you get the vs course which features not one but three complete games a simple platformer an action rpg and awesome fps in the visual scripting course all of this is built without a single line of code all games in both courses start commonly from scratch and go step by step until the final polished games all the unleashers have their project files available at every step of the way and i'm always active answering questions every single day in the q a section so if you're looking for a more guided path then check out the courses at unitycodemonkey.com courses alright hope that's useful check out these videos to learn some more thanks to these awesome patreon supporters for making these videos possible thank you for watching and i'll see you next time
Info
Channel: Code Monkey
Views: 136,743
Rating: undefined out of 5
Keywords: unity mouse position to world 3d, unity mouse position, mouse raycast unity, unity cursor position, unity click position, code monkey, physics raycast, unity raycast, unity tutorial, unity game tutorial, unity tutorial for beginners, unity 2d tutorial, unity 3d, unity, game development, game dev, game development unity, unity 2d, unity 3d tutorial, programming, coding, c#, code, software development, learn to code, learn programming, unity tutorials, how to make a game
Id: 0jTPKz3ga4w
Channel Id: undefined
Length: 10min 19sec (619 seconds)
Published: Tue Mar 23 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.