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.
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);
}
}
Ray
Physics.Raycast
RaycastHit