Please help, I am developing a 2D game for a school project and I want to drag the apple to the think box then when it collides, the apple will go back to the original position then it will add 1 point to the score. I'm just new to Unity. So please help
1 Answer
Alright, so as I'm relatively new to unity and coding myself, I don't know about drag & dropping objects, but I'm sure a quick Google search would help you out with this.
However, regarding the second part: I'll be referring to the three objects as 1, 2 and 3 and to the think boxes as a, b and c.
So you want that once 1 collides with a, 2 collides with b, etc, the score counter will go up by one, then the object will go back to its place.
First, make three new tags each with a different name for example apple, worm and pill and set them to the think box game object. This will be used to recognize which object we collided with.
Now add 2D collider components to both (all three) dragable objects and think boxes, make sure you set them to the correct size and everything, and tick "Is Trigger" on so it only detects collisions but doesn't actually block your object.
Then make a new c# script, this you will add to your dragable apple, worm and pill.
Let's make a few new variables.
public float startX
public float startY
public string collisionTag
Delete the void start and void update methods as we won't be needing them and instead add:
void OnTriggerEnter2D(Collider2D other){
if (other.gameObject.CompareTag(collisionTag)){
score++;
transform.position = new Vector2(startX, startY);
}
}
This method runs when there's a collision from a trigger, then calls this trigger other. What this does is check if the tag of the collided object is equal to the string variable collisionTag which you set in the hierarchy, and if it does, it adds one to score and puts the game object back in its starting location, x and y values you also set in the hierarchy.
We do it this way so you only have to write one script and then set the values manually, which makes it much faster and saves memory.
Now drag the script to each dragable object separately, put the desired x and y values that they'll move to when you want them to move back, and write the exact, case sensitive tag name in the collision tag box and tada! Good luck with your game.
float distance = 10; void OnMouseDrag() { Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance); Vector3 objPosition = Camera.main.ScreenToWorldPoint(mousePosition); transform.position = objPosition; }
I tried this and it is letting me drag and drop the object \$\endgroup\$