weird mouse drag behavior

I wish to make a checker game. Now I am trying to implement draggable game pieces. Here are the scripts attached to my piece GameObject:

void OnMouseDrag(){
	Debug.Log(gameObject.transform.position + " " 
		+ Camera.main.ScreenToWorldPoint(Input.mousePosition) + " " 
		+ Input.mousePosition + "

");
Vector3 convertedPos = new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
0,
Camera.main.ScreenToWorldPoint(Input.mousePosition).z);
gameObject.transform.position = convertedPos;
}

I have an orthographic looking-downwards camera at (0,70,0).
When I tried to drag the pieces, in some cases it works fine. In other case the pieces moved are not the ones I dragged.

OnMouseDrag() will only be called if you clicked on the collider for that object, and that collider has to be the first collider at this position. Maybe you have an oversized collider on one or more of your objects?

2 Answers

2

So i assume you have the right z parameter which is distance between camera and the object.
If not try this:

private float floatZ;
void OnMouseDown()
    {
        floatZ = Vector3.Distance(Camera.main.transform.position, this.gameObject.transform.position);
    }

    void OnMouseDrag()
    {
        this.gameObject.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, floatZ));
    }

Just for reminder OnMouse doesn’t work on mobile, use Input.GetMouseButton instead , this works on multiple platform.But it can not automatically select your object

i fixed it.
the capsule collider of some pieces are not correctly sized.