RayCasts and Collision

Hi, probably a simple solution to this but just cant think how to do it sorry.

I’ve done a ray cast eg.

if(Physics.Raycast(ray, hit))
{
   //Debug.Log(hit.collider.name);
   if ((hit.collider.name) && Input.GetMouseButtonUp(0))
   {

     Destroy(hit.collider.gameObject,2);

   }

}

So when the mouse button is clicked over several different objects they disappear after 2 seconds which works all good.

What I want to do is, move each object individually when they are clicked on. This script is attached to all the objects that I want to click on and then translate. I hope this makes sense, I don’t quite understand when moving objects (its only for 2 seconds in this case) how I can keep track of each one as a few objects could have been clicked on within those 2 seconds…All objects have been placed in the scene, not instantiated in code…

Thanks for any assistance!:slight_smile:

If you want to click every object, use OnMouseDown().

The way you are using rays now is very inefficient and will get you into trouble.

Id rather try and get this way working as once I’ve solved this I’m done, thanks for the suggestion but chose rays as up until now easy to implement. I had other issues with onmousedown which caused me a headache in the way in which it worked, can’t actually remember the details but hence why i thought id try using Rays…

what i did in the end was add a rigid body to all the objects and took gravity off, then i put this line in the script

hit.collider.gameObject.rigidbody.useGravity=true;

The natural way to do this is using coroutines, I guess.

using System.Collections;
using UnityEngine;

public class Test : MonoBehaviour
{
   void Update()
   {
     if (Input.GetMouseButtonUp(0))
     {
       var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

       RaycastHit hit;
       if (Physics.Raycast(ray, out hit))
       {
         Destroy(hit.collider.gameObject, 2);
         StartCoroutine(Translate(hit.collider.gameObject));
       }
     }
   }

   IEnumerator Translate(GameObject go)
   {
     while (go != null)
     {
       go.transform.Translate(Vector3.forward * Time.deltaTime);
       yield return null;
     }
   }
}

Hey Alex, thanks for the reply, I’ll try and go through your code, although using javascript at the moment, i’m not too hot on c# …