I would like to receive mouse click coordinates on the plane so that I can tell my character to go in that direction. So in pseudocode it will look like :
Use Camera.ScreenPointToRay to get a ray starting at the camera’s near plane and shooting out where the mouse would be:
Using that ray, raycast to hit your plane. The hit location is where they clicked.
Thanks for the quick response. I get your idea on how to do this but to be honest I am a real newbie in terms of Unity. Can you help me on that ?
I keep getting this error after having attached this script to my Cube object
How can I attach the camera to Cube ?
ummm… you probably don’t want a camera attached to the cube…
when I say ‘Camera.ScreenPointToRay’ just like the linked documentation does, that means the ‘the function ScreenPointToRay defined on the class Camera’. You need a reference to a camera first and foremost.
You’re probably saying in your code:
camera.ScreenPointToRay(…)
which is the same as
this.camera.ScreenPointToRay(…)
note the case, unityscript and C# are case-sensitive with their names of things. So Camera and camera are two different things. Camera being the class Camera, camera being a reference to a camera attached to the gameobject that owns this script. But it may not actually exist… and probably doesn’t for the most part.
Even if there was, it probably wouldn’t be your main camera. You want this ray from your main camera.
So you need to call Camera.main:
So you’d say:
Camera.main.ScreenPointToRay
Ok, now it works but I still don’t know how to get the coordinates of mouse position on the plane, or as you wish - mouse pointer projection on the plane that the character is walking on.
so you pass in the screen mouse position to this function, which creates a ray for you (read the documentation that I linked for what the ray looks like).
You get the mouse position from Input.mousePosition:
Now with that ray you need to do a Raycast…
note the necessity of a collider for Physics.Raycast. But in the same respect, it’s not the only way to perform raycasts, it’s just the normal way of doing it in Unity3d.
Go read those documentations, and try working with it.
Thanks a lot
yet!.. the code in the documentation
gives me an error :
I have trying to assign the result of Instantiate to something like UnityEngine.Object but I kept getting errors.
you don’t need that instantiate thing… that’s just example code. That instantiate is just an example of a particle appearing where was clicked.
How can I do by using Camera.ScreenToWorldPoint