- Home /
How can I drag just one object, but not all the objects ? (Android)
I'm making a 2D puzzle game on android. My code was working fine when I was only working with one object. But then I added more objects and now when I touch one of the puzzle pieces , I'm dragging all of the puzzle pieces on the screen. By the way, this script is attached to all pieces. Here's my code :
public Transform right_particle;
public Transform wrong_particle;
public string pieceStatus = "";
void Update()
{
if (pieceStatus != "locked" && Input.GetMouseButton (0)) {
float distance_to_screen = Camera.main.WorldToScreenPoint (gameObject.transform.position).z;
Vector3 pos_move = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, distance_to_screen));
gameObject.transform.position = new Vector3 (pos_move.x, pos_move.y, pos_move.z);
}
}
void OnTriggerStay2D(Collider2D other)
{
if ((other.gameObject.name == gameObject.name) && Input.GetMouseButtonUp(0) ){
other.GetComponent<BoxCollider2D> ().enabled = false;
GetComponent<BoxCollider2D> ().enabled = false;
transform.position = other.gameObject.transform.position;
pieceStatus = "locked";
Instantiate (right_particle, other.gameObject.transform.position, right_particle.rotation);
}
else if ((other.gameObject.name != gameObject.name) && Input.GetMouseButtonUp (0)) {
Instantiate (wrong_particle, other.gameObject.transform.position, right_particle.rotation);
}
}
I've also tried with raycasting but none of the pieces moved. I also have one more problem with the OnTriggerStay2D, "else if" part. OnTriggerStay2D should instantiate one of the particles according to puzzle piece is in the correct place or not. But it instantiates both of them when piece is in the correct place. I can use any help especially with the first question. Thank you everyone.
Answer by almonmanzano · Jan 12, 2018 at 04:32 PM
Hello! The problem is that Input.GetMouseButton(0) returns true when the left button of the mouse is pressed (no matter where the pointer is). If you want to check if the pointer clicks over and drag an object, you should use OnMouseDrag(). If you change Update() for OnMouseDrag() you can solve your problem, and you can remove the Input.GetMouseButton(0) condition. Regards! ;)
Thanks a lot ! I've changed Update() method with On$$anonymous$$ouseDrag() and now I can move all the pieces without any problem. Also, I've swapped the contents of if() and else if() parts, now I can get the particles correctly but there's just one piece always instantiate both of the particles when it is placed correctly. Any idea how can I fix this ?
You're welcome! Seems like OnTriggerStay2D is being called 2 times (with 2 different Collider2D). Try adding Debug.Log("instantiating right particle when colliding with " + other.name) and Debug.Log("instantiating wrong particle when colliding with " + other.name) and, if you still need help, paste here the output.