26 de mai de 2017

Physics2D.Raycast

An example of how to use Raycast to show the path where the Gameobject will pass.
A tip is, you must disable Edit > ProjectSettings > Physics2D > Queries Start in Collider
This mean that the Raycast will not collide with the Collider where it starts in.


public int numPositions = 3;
public Vector3 diretion = new Vector2(1, 1);
public LineRenderer lineRenderer;
void UpdateLineRenderer()
{
    Vector3 actualDirection = diretion;
    Vector3 actualPosition = transform.position;
    Vector3 lastPosition = actualPosition;

    lineRenderer.SetPosition(0, actualPosition);

    for (int x = 1; x < numPositions; x++)
    {
        RaycastHit2D hit = Physics2D.Raycast(lastPosition, actualDirection);
        lineRenderer.SetPosition(x, hit.point);
        lastPosition = hit.point;

        actualDirection = Vector3.Reflect(actualDirection, hit.normal);
    }
}


We can use the Debug.DrawRay to see the Raytrace:


Debug.DrawRay(transform.position, diretion*100);

Nenhum comentário: