- Home /
how do i attach an object to the mouse on click
I wish to attach an object to the mouse when the mouse button is down and the object is released when mouse button is up. How can i do that ? (I have a version where the object moves after the mouse but i drop the object when i move the mouse too fast)
Sounds like you're trying to grab the object beneath the cursor each frame. Ins$$anonymous$$d, you should lock onto it when L$$anonymous$$B is down, and release it when L$$anonymous$$B is up.
Yes you are right AlwaysSunny, I am using raycast to get the object info (with hitInfo) , then assign mouse position to the hitInfo, but indeed it is for each frame. How then can i lock the object onto the mouse or mouse position?
If possible, only do the raycast check On$$anonymous$$ouseButtonDown()
Assign the gameobject you clicked to a variable using the hit info
If that variable is not null, move its transform with mouse input
if it is null, do nothing
Set it to null On$$anonymous$$ouseButtonUp()
thank you, that is where I am stuck, not sure how to "Assign the gameobject you clicked to a variable using the hit info". (should I use GameObject.Find?)
Answer by AlwaysSunny · Oct 29, 2014 at 06:16 AM
Transform dragObject;
void Update() {
if (dragObject) {
// dragObject not null, move it according to mouse input
}
if (Input.GetMouseButtonDown(0)) {
RaycastHit hitInfo = new RaycastHit();
if ( Physics.Raycast( Camera.main.ScreenPointToRay( Input.mousePosition ), out hitInfo )) {
dragObject = hitInfo.collider.transform;
}
}
if (Input.GetMouseButtonUp(0)) {
dragObject = null;
}
}