- Home /
Clicking and dragging a gameObject
I am currently dragging a gameobject like this.
Vector3 screenSpace;
Vector3 offset;
void OnMouseDown()
{
//translate the cubes position from the world to Screen Point
screenSpace = Camera.main.WorldToScreenPoint(transform.position);
//calculate any difference between the cubes world position and the mouses Screen position converted to a world point
offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y, screenSpace.z));
}
private float speed = 7.5f;
void OnMouseDrag()
{
Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
transform.position = curPosition;
}
}
Sometimes a user doesn't click directly on an object so is there a way that if a user is between 3-7 pixels off, it still counts as a click. Any help is appreciated.
Answer by VesuvianPrime · Jan 31, 2015 at 08:00 PM
Is it an adequate solution to increase the size of your colliders?
Perhaps you could add a child GameObject with a collider on a different layer?
I cannot increase the size of my colliders as I am using them for physics. But, how would I go about detecting touch on a child gameobject that is on another layer?
Simply create an empty GameObject, attach a Collider component, set the layer of the GameObject and attach something like this:
public class $$anonymous$$ouseCollider : $$anonymous$$onoBehaviour
{
public $$anonymous$$yClickableScript target;
void On$$anonymous$$ouseDown()
{
if (target != null)
target.$$anonymous$$yClick$$anonymous$$ethod();
}
}
This is extremely rough, but I think you get the idea.
Ah ok, thanks for the advice. I'm going to try it now.