- Home /
How can I find if a raycast has passed through two points?
I am making a raycast-based navigation system (because I'm too poor for pro :/) and I need it to be dynamic (respond to new objects) and I need to see if a raycast has gone between two points (and passing through) so I can tell if I have already had my character go that way so he can choose another way to go. Is this possible? Thanks in advance - you people are the best!
If you look at my image, I would like to detect if a line from C to D passes between points A and B at the intersection where the red X is.
having a hard time figuring out your request. are you trying to get 2 raycasts to hit each other?
This can be calculated. But does this system work in two or three dimensions? ($$anonymous$$akes a lot of difference :p)
Answer by smallbit · Jul 23, 2014 at 01:17 AM
You could create a mesh collider (plane) on a run between A and B with some height (must be relatively high depending on flatness of your level).
Raycast C-D
On Found D create mesh collider
Raycast Again same direction
If hit your mesh set some flag or continue with your code.
Just a theory never tried it.
Answer by WilliamLeu · Jul 23, 2014 at 01:28 AM
You're probably best off looking for a 3D line to line collision test off Google and porting it to Unity (unless you need a 2D test, which is faster to calculate).
See if this works for you (ported from StackOverflow)
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
bool LineLineIntersection3D(
Vector3 LineA_Pt1,
Vector3 LineA_Pt2,
Vector3 LineB_Pt1,
Vector3 LineB_Pt2, out Vector3 IntersectionPt)
{
Vector3 da = LineA_Pt2 - LineA_Pt1;
Vector3 db = LineB_Pt2 - LineB_Pt1;
Vector3 dc = LineB_Pt1 - LineA_Pt1;
if (Mathf.Abs( Vector3.Dot(dc, Vector3.Cross(da,db) ) ) > Mathf.Epsilon ) // lines are not coplanar
{
IntersectionPt = Vector3.zero;
return false;
}
float s = Vector3.Dot( Vector3.Cross(dc,db),Vector3.Cross(da,db)) / Vector3.Cross(da,db).sqrMagnitude;
if (s >= 0.0f && s <= 1.0f)
{
IntersectionPt = LineA_Pt1 + da * s;
return true;
}
IntersectionPt = Vector3.zero;
return false;
}
// USAGE EXAMPLE
void Awake()
{
Vector3 v3Intersection;
if( LineLineIntersection3D(
new Vector3( -1.0f, 0.0f, 0.0f ), // Point A
new Vector3( 5.0f, 0.0f, 0.0f ), // Point B
new Vector3( -1.0f, 0.0f, 3.0f ), // Point C
new Vector3( 5.0f, 0.0f, -7.0f ), // Point D
out v3Intersection ) )
{
Debug.Log( "Intersection at " + v3Intersection.ToString( "F4" ) );
}
}
}
Your answer
Follow this Question
Related Questions
AI Field of vision 1 Answer
Another Raycast Issue. 0 Answers
How do you create an AI that works like this ? 1 Answer
nav mesh agent not following properly 0 Answers
Way to find closest point in a specific area on navmesh. 0 Answers