- Home /
Can't Make Raycast Target Nearest Character
I'm trying to make it so that when the player hits the spacebar a raycast is shot at the nearest target. I had no idea how to do it so I researched some tutorials and looked at some documentations. Doing That left me with this code and now im just stuck.
Thanks in advance :)
[SerializeField] float Damage = 1f;
[SerializeField] float MaxRange = 10f;
public Transform Grappling_Hook;
public Transform target;
public Vector3 TriggerSphere;
public void GrappleAble(Transform Position)
{
}
private void OnTriggerStay(Collider other)
{
Collider[] HitColliders = Physics.OverlapSphere(TriggerSphere, 10f);
List<GrapplingHook> Grappables = new List<GrapplingHook>();
foreach(Collider X in HitColliders)
{
Grappables.Add(new ) //Wont Allow Me To Put The Grappables Class In
}
}
void Update () {
if(Input.GetButtonDown("Space"))
{
Shoot();
}
}
void Shoot()
{
RaycastHit HitInfo;
var heading = target.position - Grappling_Hook.position;
var distance = heading.magnitude;
var direction = heading / distance;
if (heading.sqrMagnitude < MaxRange * MaxRange)
{
Physics.Raycast(Grappling_Hook.transform.position, direction, out HitInfo);
}
}
}
Comment
Answer by ray2yar · Dec 27, 2018 at 04:47 PM
I suggest narrowing your options some, create a public LayerMask and put in it the different layers of objects you want to raycast toward. Then I'd do a Physics.OverlapSphere - this will get all the colliders within the sphere. You can check through them and find the shortest distance. The code below does just that. You can Raycast toward the Vector3 "closestPoint" or toward the "closestGameObj"
public LayerMask castObj;
float maxRadius;
void FindClosest()
{
float distance=maxRadius+1f;
Vector3 spot = Vector3.zero;
GameObject closestObj = null;
Vector3 closestPoint = Vector3.zero;
foreach(Collider col in Physics.OverlapSphere(transform.position,maxRadius,castObj))
{
spot = col.ClosestPoint(transform.position);
if ((spot - transform.position).magnitude < distance)
{
distance = (spot - transform.position).magnitude;
closestObj = col.gameObject;
closestPoint = spot;
}
}
}