- Home /
Issue to destroy objects using RaycastHit2D when instantiated from 2D Sprite and they are in motion, i.e. falling against gravity?
I am quite new to Unity and stuck in one problem for couple, of days. Earnestly need suggestion or help to resolv![alt text][1]e the issue. [1]: /storage/temp/149031-issue-in-destroying-objects-when-its-in-motion.jpg
Problem: Can destroy the balloon in mouse click when instantiated and not yet started its falling against gravity. But, can't destroy it with same mouse click when it starts falling. Please find attached screenshot for details.
Code using to hit the object using RaycastHit2D:
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y, 10)), Vector2.zero, animalLayer);
// Here Z= 10, because Transform position of Main Camera Z= -10.
if (hit.collider != null && hit.collider.tag == "Balloon ") { Debug.Log(" Clicked Object " + instantiatedObj.name); }
I feel, I need to incorporate the changed position of the balloon where it's attached RigidBody 2D components are as follows:
i.e. Mass = 1, Linear Drag =0, Angular Drag = 0.05, Gravity Scale= 0.02
Thanks a lot in advance.
Answer by BarunKumarBairagi · Dec 07, 2019 at 02:32 PM
[Solved] The issue is solved by the following way:
Step 1: Create a class from IPointerClickHandler
e.g. public class TestEvent : MonoBehaviour, IPointerClickHandler)
Step 2: Implement OnPointerClick() e.g. public void OnPointerClick(PointerEventData eventData) { if(eventData.pointerCurrentRaycast.gameObject != null)
Destroy(gameObject); // Delete the object.
}