- Home /
How to add a score when the correct object drags to the correct box?
I have created a 2d drag and drop game using mouse control. But I don't know how to add a score when the correct object drags to the correct box. what I need is, when the object overlaps the correct object the score must be increased. This is my code,
public class Drag : MonoBehaviour{
public GameObject correctForm,carrot,circle;
private bool moving;
private bool finish;
private float startPosX;
private float startPosY;
private Vector3 resetPosition;
void Start()
{
resetPosition = this.transform.localPosition;
}
void Update()
{
if(finish == false)
{
if (moving)
{
Vector3 mousepos;
mousepos = Input.mousePosition;
mousepos = Camera.main.ScreenToWorldPoint(mousepos);
this.gameObject.transform.localPosition = new Vector3(mousepos.x - startPosX, mousepos.y - startPosY, this.gameObject.transform.localPosition.z);
}
}
}
public void OnMouseDown()
{
if(Input.GetMouseButtonDown(0))
{
Vector3 mousepos;
mousepos = Input.mousePosition;
mousepos = Camera.main.ScreenToWorldPoint(mousepos);
startPosX = mousepos.x - this.transform.localPosition.x;
startPosY = mousepos.y - this.transform.localPosition.y;
moving = true;
}
}
public void OnMouseUp()
{
moving = false;
if(Mathf.Abs(this.transform.localPosition.x - correctForm.transform.localPosition.x) <= 0.5f &&
Mathf.Abs(this.transform.localPosition.y - correctForm.transform.localPosition.y) <=0.5f)
{
this.transform.position = new Vector3(correctForm.transform.position.x, correctForm.transform.position.y, correctForm.transform.position.z);
//MyscoreText.text = "Score : " + ScoreNum;
//Destroy(coin);
finish = true;
if(moving == false)
{
Score.ScoreNum += 2;
}
}
else
{
this.transform.localPosition = new Vector3(resetPosition.x, resetPosition.y, resetPosition.z);
}
}
}
Answer by eneIr · May 28, 2021 at 12:05 PM
In short, you should use OnDrag() and OnDrop() (add IDropHandler next to Monobehaviour). For more details, you can search Drag and drop in unity on YouTube, there're lots of tutorials.
Your answer
Follow this Question
Related Questions
How to add score after destroying object in unity 2D? 1 Answer
Clicking on one object to destroy a specific number of tagged objects dragged sidebyside 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to create a Drag & Drop system which verifies what gameObject was dragged into the slot? 0 Answers