- Home /
Following the cursor...
Hello. I want an object in my game to follow the player's mouse cursor y position (regardless of whether they are holding down the mouse buttons or not). I think I know what I have to do (construct a ray from the cursor to a collider, convert that to world space, and then set the object's transform.position.y equal to that number)...I just cannot figure out how to do it. I have the ray part of the script, but how do I convert it to a Vector3 (I am guessing it has something to do with this, I just do not know how to implement it). Thanks.
var MyCursor : Vector3;
function Update(){
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
transform.position.y=MuCursor.y;
}
Read this page of the wiki and take what you need for your situation.
Answer by robertbu · Mar 20, 2013 at 11:27 PM
If you know the distance form the camera you want to place the object, then Camera.ScreenToWorldPoint() is a nice solution.
function Update() {
var pos = Input.mousePosition;
pos.z = distance_to_object;
transform.position = Camera.main.ScreenToWorldPoint(pos);
}
Thanks for the reply. When I use this, the object's x position goes a little off (it always goes just off the screen...I have even tried using pos.x=-8.2, which is where I want my object to be). Also, is there a way to not have the object follow the cursor of the cursor is going off screen (I have tried transform.position.clam.y=..., but no luck).
The distance_to_object must be a positive value. It is the distance in front of the camera. So if your camera is in the typical setup where it is -10 on the z axis, and you want the objects to have a 0 z value, you would use a value of 10.
Is that just for the z axis? I already have my pos.z value at 10.
It has nothing to do with the axis. It is how far in front of the camera no matter which way the camera is facing. Here is another script. Put a point light or two in a scene and attach this script to an empty game object, and click away. Rotate the camera in the inspector and click some more.
function Update () {
if (Input.Get$$anonymous$$ouseButtonDown(0)) {
var v3 = Input.mousePosition;
v3.z = Random.Range(3.0, 18.0);
v3 = Camera.main.ScreenToWorldPoint(v3);
var go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
go.transform.position = v3;
}
}
Answer by AlucardJay · Mar 21, 2013 at 04:19 AM
Check my answer here : http://answers.unity3d.com/questions/406636/3d-object-attach-to-mouse-1.html
Your answer
Follow this Question
Related Questions
Why is Input.GetAxisRaw() not returning whole numbers when using a joystick? 1 Answer
Input Touch.position 'inverted' relative to screen? 1 Answer
How to keep position on input.get axis even when it is pressed twice? 1 Answer
Instantiating an object at click position 2 Answers
Scrollview with Input.MousePosition? 1 Answer