- Home /
Question by
floralDenis · Dec 18, 2016 at 08:01 AM ·
2draycastraycastingray
Problem with raycast distance
I want to have constant distance at which the raycasting should stop, but script ignore distance parameter. Help me please. Thank in advance.
void Update()
{
float distance = 0.3f;
Vector2 myvec = transform.position + target.position;
RaycastHit2D hit = Physics2D.Raycast(transform.position, -myvec,distance);
Debug.DrawRay(transform.position, -myvec, Color.yellow);
if (hit.collider != null)
{
print("hitted");
if(hit.collider.gameObject.CompareTag("earth"))
print("hit");
}
}
Comment
Your Debug.DrawRay
does not account for the distance, so it only shows the direction. Are you sure it isn't working as intended?
Shouldn't it be
Debug.DrawRay(transform.position, -myvec.normalized * distance, Color.yellow);
if you want your ray to go to Target.position, you are calculating direction wrong way.
Vector2 dirToTarget = target.position - transform.position;
RaycastHit2D hit = Physics2D.Raycast(transform.position, dirToTarget, distance);
Best Answer
Answer by ElijahShadbolt · Dec 20, 2016 at 02:16 AM
void Update()
{
float distance = 0.3f;
Vector2 myvec = target.position - transform.position; // from transform to target
RaycastHit2D hit = Physics2D.Raycast(transform.position, myvec, distance);
Debug.DrawRay(transform.position, myvec.normalized * distance, Color.yellow);
if (hit.collider != null)
{
print("hitted");
if (hit.collider.gameObject.CompareTag("earth"))
print("hit");
}
}