- Home /
How can i get raycast hit from a specific gameobject ?
The script is attached to a moving gameobject. I want to detect when the gameobject is above another gameobject.
In the top of the script i added:
Collider col;
Then in the Start:
baseTarget = GameObject.Find("Base").transform;
col = baseTarget.GetComponent<Collider>();
I want to detect a hit when the transform is above the baseTarget.
Then in the Update
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (col.Raycast(ray, out hit, 100.0F))
{
Debug.Log("Hit !");
}
But it's not working. I don't want to use the mouse for that.
Answer by Larkman · Jun 28, 2017 at 11:20 AM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GroundDetector : MonoBehaviour {
private Ray ray;
// "hit" variable stores information.
private RaycastHit hit;
// drawing vector's direction.
[SerializeField]
private Vector3 direction = new Vector3(0f, -1f, 0f);
// distance of vector.
[SerializeField]
private float distance = 10f;
// using offsetY for ignoring gameObject itself. If you do not want to offset the ray, you can use layerMask as Physics.Raycast method's 4th parameter.
[SerializeField]
private float offsetY = -0.6f;
void Start () {
ray = new Ray(new Vector3(gameObject.transform.position.x, gameObject.transform.position.y + offsetY, gameObject.transform.position.z), direction);
}
// Use this for initialization
void Update () {
// gameObject's position is changing over time.
ray.origin = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y + offsetY, gameObject.transform.position.z);
if (Physics.Raycast(ray, out hit, distance)) {
Debug.Log(hit.collider.gameObject.name, hit.collider.gameObject);
}
// Draw ray for visualition.
Debug.DrawRay(ray.origin, ray.direction * distance, Color.green, 1f);
}
}
This is working great.
And if i have another GameObject in the Hierarchy that is position is on the Terrain. I did in the Start
void Start()
{
GameObject go = GameObject.Find("Base");
ray = new Ray(new Vector3(gameObject.transform.position.x, gameObject.transform.position.y + offsetY, gameObject.transform.position.z), go.transform.position);
}
The GameObject is "Base" (A cube) And i want that it will detect the "Base" but it keep detecting the Terrain. I replaced the direction with the "Base" go.transform.position
Are you sure that ray's origin starts outside of "Base" game object's collider? RaycastHit hits the surface of collider. If you want to check that if 2 objects' colliders are nested or not, you might use OnTriggerEnter OnTriggerExit OnTriggerStay