- Home /
Following mouse
Alright so I hate to ask a question on something so broad but im not sure were to start. I want a platform to follow my mouse when it moves. To do this i figured if i could find a way to convert my mouse position to a world position and set that to a variable then i could measure the change and work form there. The only thing is that i dont know how to do really anything with the mouse and so was wondering. How can I set the mouses position as a variable? also i use C#
Answer by aldonaletto · Aug 24, 2012 at 02:16 AM
You could cast a ray from the camera that passes through the mouse point, and get the position where this ray hits something - this is useful when you want the platform to keep a constant height above the ground:
float height = 3; // height above the ground Transform platform; // drag the platform here
void Update(){ // create a ray passing through the mouse pointer: Ray ray = camera.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)){ // if something hit... // move the platform to the hit point: platform.position = hit.point + height * Vector3.up; } }
God is all you do is sit on your computer and answer questions i see you everywere(i do not mean this as a bad thing). And ill give this a try.
Alright so i tried it and weather it worked or not im not tottaly sure as i left some out.(the part about the height as thats not what i need) So let me try to be a bit more specific all i need as i believe i can get the rest to work out is to be able to convert my mouse position into a vector2 world position.
$$anonymous$$y wife says the same - but she thinks this IS a bad thing! (girls hate when we have fun without them...) The problem is: a 2D screen point corresponds to an infinite line in the 3D world. To get a single point, you must find where this line intersects a plane (or the ground, in the case above). If you place a big plane in front of the camera (at some distance - 20 units, for instance), the script below can return a reliable 3D point:
Vector3 hitPoint;
void Update(){ // create a ray passing through the mouse pointer: Ray ray = camera.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)){ // if something hit... // get the hit point: hitPoint = hit.point; } } The hitPoint variable has the 3D coordinates of the plane point that lies "under" the mouse pointer.
NOTE: Attach this script to the camera
"$$anonymous$$y wife says the same" Hey I appreciate anyone taking the time to review and answer my questions. So thanks for supporting the community.
ill be trying that soon i just have a few more codes to right before im at that point again
Your answer
Follow this Question
Related Questions
Camera rotation around player while following. 6 Answers
Move an object towards a point using raycast from Main Camera 2 Answers
Multiple Cars not working 1 Answer
Camera Rotate to mouse position -2 Answers