#Raycasting in unity | #Ray cast hit detection unity c# in less than 1 min | Code in description
using UnityEngine;
/*
Logic : A ray is cast in forward direction. If it hits anything color of ray changes to yellow
else it will be white. You can perform the activity on hit detection
*/
public class RaycastHitdetection : MonoBehaviour
{
////// it is better to perform physics related work in fixed updated rather than update ////////
void FixedUpdate()
{
RaycastHit hit;
// Syntax : Physics.Raycast(Vector3 startPosition,Vector3 direction e.f transform.forward/up, out hit, float distance));
bool hasHit= Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity);
// Does the ray intersect any objects
if (hasHit==true)
{
////////// this simply draws a ray from transform object till the object it has hit /////////
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Did Hit");
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
Debug.Log("Did not Hit");
}
}
}