- Home /
how to drag an object using 2d raycasts
Hi, I am making a kids game where three shapes randomly generate and you have to drag the shape to a monster(right now its a square but it will be a monster) who checks to see if it is the right shape or not. I am having problems with the dragging bit.I have been trying to use RaycCasting to get information on the object that i clicked then snap the object that I clicked to the mouse until the mouse is let go when I use GetMouseButtonUp to see when let go. I kinda got this working but I couldn't get it to work in 2D (not because of using the wrong colliders but not being able to convert from 3D to 2D) So to put it simple how do I drag an object using the mouse then when I let go it has touched or is in the right spot? ps right now when I click a shape it disappears.  `using UnityEngine;
`using UnityEngine;
public class ShapeScript : MonoBehaviour { public Camera cam; private GameObject shape; private Vector2 mouse;
 void Update()
 {
     mouse = Input.mousePosition;
     Ray ray = cam.ScreenPointToRay(mouse);
     RaycastHit hit;
     if (Physics.Raycast(ray, out hit, 100))
     {
         if (Input.GetMouseButton(0))
         {
             if (hit.transform.tag == "PickUp")// if it is a shape
             {
                 shape = hit.transform.gameObject;
                 shape.transform.position = Input.mousePosition;// move it to the mouse position
             }
         }
         if (Input.GetMouseButtonUp(0))
         {
             if (GameObject.Find("Monster").GetComponent<MonsterScript>().rightSpot == true)// if its in the right spot when let go
             {
                 Destroy(shape);
                 if (GameObject.Find("Spawner").GetComponent<SpawnPickUps>().correctShape == shape.transform.name)//if the shape = the correct shape
                 {
                     Debug.Log("right");
                 }
                 else
                 {
                     Debug.Log("wrong");
                 }
             }
         }
     }
 }
}
` and I also have a script on my monster to see if the are touching
 using UnityEngine;
 
 public class MonsterScript : MonoBehaviour
 {
 
     public bool rightSpot = false;
 
 
     public void OnTriggerEnter(Collider other)
     {
         if(other.tag == "PickUp")
         {
             rightSpot = true;
         }
     }
     public void OnTriggerExit(Collider other)
     {
         if(other.tag == "PickUp")
         {
             rightSpot = false;
         }
     }
 }
Please let me know if you need more information If you can't tell I'm new to coding so please try and make it simple
and thank you.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                