Hello,
heres whats happening, i was trying to raycast from a drone to a player and i didint get any hit from the raycast
so i checked it by drawing Debug.DrawRay and you can see whats happening the ray should be in the player direction but it isn’t.I dont know what do do now, i dont know where the problem is , and maybe you can guys help me
void OnTriggerStay2D(Collider2D coll)
{
if (coll.tag == "Player")
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, coll.transform.position, Mathf.Infinity);
Debug.DrawRay(transform.position, coll.transform.position);
if (hit.collider != null)
{
if (hit.transform.tag == "Player")
{
Debug.Log("hit");
}
}
}
}
See how parameter 2 says it requires a direction.
You’re providing it the position of the desired target instead. That’s why you’re getting unexpected results.
Direction vectors are calculated by subtracting the origin position from the destination position.
var direction = transform.position - coll.transform.position
Think of a vector2 as a point on a graph. It has an X and a Y co-ordinate.
You can think of it as representing a position, or you can think of it as representing both direction and magnitude (length).
Let’s say we have the vector2 with the value +2,+2.
If we consider that to be a position, then the position is at +2,+2 on the graph, easy.
If we consider that to be a direction+magnitude, then we draw a line from 0,0 on the graph to +2,+2 on the graph. The direction is the direction the line points away from 0,0 and the magnitude is how long the line is.
If we have 2 positions, then the direction and magnitude from one to the other is just the difference between their values.
pointA - pointB = the direction from pointB to pointA
pointB - pointA = the direction from pointA to point B
The raycast function wants a vector2 representing a position for its first parameter, and a vector2 representing a direction for its second.