- Home /
Collision with object using MouseDrag
Hey, I'm trying to use OnMouseDrag()
to detect colision with the object I drag, like Fruit Ninja, but it don't detect colision
I used using UnityEngine; using System.Collections;
public class MouseDrag : MonoBehaviour {
void OnMouseDrag()
{
print ("worked");
Destroy(this.gameObject);
}
}
It dont print and don't destroy the gameobject, I need to use some colision enter or something like that ? I want to detect collision only when I'm dragging
Answer by tungnguyendev · Mar 27, 2014 at 02:44 PM
You need add collider componant to your gameobj to detect collision. this is code i make with unity2d
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint (curScreenPoint) + offset;
transform.position = curPosition;
}
and detect collision
void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "your_gameobj_for_collision") {
Destroy(gameObject); } }
and sure set trigger of collider componant = false :D
Whats each variable is ? They are not declared screenPoint && offset are gameObject ?
@tungnguyendev can you give me the code in javascripts please :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613141318im_/https://answers.unity.com/themes/thub/images/avi.jpg)