i’m using one of the overloads for Physics2d.Raycast and my compiler (just visual studio) doesn’t like it:
void HandleClick(Vector3 clickPos)
{
Ray ray = Camera.main.ScreenPointToRay(clickPos);
//RaycastHit2D hit;
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
Debug.DrawLine(transform.position, clickPos, Color.red);
if (Physics2D.Raycast(ray, out hit, 100))
{
if (hit.collider.tag == "Enemy1")
EnterState(State.ApproachingEnemy);
}
else
{
targetPos = clickPos;
EnterState(State.WalkingToSpot);
}
}
i don’t know where i got ray.origin and ray.direction from. a mouse position cannot have a direction. that’s probably what’s wrong. it gives the error at Physics2D.Raycast(ray, out hit, 100) - on the first two arguments, ray and out hit. i might be able to fix this on my own before anyone gets to it but … we’ll see.
edit: i changed hit to Physics2d.Raycast(transform.position, ray.origin).
still saying the two parameters i mentioned above are wrong. to give more detail, i am trying to cast from the hero object (to which the script is attached) to a position where the mouse is clicked.
edit2: i eventually settled with
if (Physics2D.Raycast(transform.position, direction1, 10)) …
but my debug line isn’t even drawing. it’s a small state machine, i’m not sure what’s wrong.
here’s how my code is now:
void HandleClick(Vector3 clickPos)
{
//Ray ray = Camera.main.ScreenPointToRay(clickPos);
var heading1 = clickPos - transform.position;
var distance1 = heading1.magnitude;
var direction1 = heading1 / distance1;
Ray ray = new Ray(transform.position, direction1);
//RaycastHit2D hit;
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction1);
Debug.DrawLine(transform.position, clickPos, Color.red, 10);
//if (Physics2D.Raycast(ray, out hit, 100))
if (Physics2D.Raycast(transform.position, direction1, 10))
{
if (hit.collider.tag == "Enemy1")
EnterState(State.ApproachingEnemy);
}
else
{
targetPos = clickPos;
EnterState(State.WalkingToSpot);
}
}