0
\$\begingroup\$

I've been coding a program to teleport an object to a player hands(which is just and empty game object). I did this using ray collision on mouse down, but I cant think of a way to find the position of the object I'm trying to teleport. I'm using GameObject.Find to find position of the hands, but I wanted to know if there was a way to find the position of an object via a ray collision. If there isn't a way to find the position of an object from a ray collision what other way could I find its position.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BasicCollisonSound : MonoBehaviour {
    public Transform hands;
    public Transform obj;

    void Start()
    {
        hand = GameObject.Find("Hand");
    }



    void Update () {
        if (Input.getkeydown("mouse1"))
        {

            Ray ray;
            RaycastHit hit;

            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if(Physics.Raycast(ray, out hit, 100.0f))
            {
                if (hit.collider.tag == "Grabbable")
                {

                    obj.position = hands.position;
                }
            }





        }
    }
}
\$\endgroup\$
1
\$\begingroup\$

You can use hit.transform to access the transform property of the object your ray hit. Then you can just set the position from there. (Code not tested, please comment on whether it works or not)

if(Physics.Raycast(ray, out hit, 100.0f))
{
     if (hit.collider.tag == "Grabbable")
     {
          hit.transform.position = hands.position;
     }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.