0
votes

I am attempting to get a LineRender to rotate with a GameObject. I want it to start at the center of its parent GameObject and extend till it encounters another GameObject. Much like how a laser pointer would work if you were standing in a room and rotating around.

enter image description here

The below code semi-works in that it shoots a LineRenderer to the center of any GameObject as it rotates. So it jumps. This is the example C red line in the picture above.

Additionally, my "walls" are in a Unity tilemap with the tag of "block", so the only objects that are returning valid to the RayCast2D are the ones outside of the tile map. The walls do have TileMap Collider 2D attached.

Lines A and B are representative of what I would like to happen. But, those not show up as the walls are in a tile map.

Any help?

private LineRenderer lineRenderer;
private int xRot = 0;    
private void Awake() {
        lineRenderer = GetComponent<LineRenderer>();

        if (lineRenderer != null) {

            lineRenderer.transform.position = new Vector3(transform.position.x, transform.position.y, -3); // Put this higher up so the camera can see
            lineRenderer.startWidth = 0.2f;
            lineRenderer.endWidth = 0.2f;
            lineRenderer.useWorldSpace = true;
            lineRenderer.SetPosition(0, transform.position);
        }
    }


    private void void Update() {

        transform.rotation = Quaternion.Euler(0, 0, xRot);
        xRot++;
        xRot = (int)Mathf.Repeat(xRot, 360);

        Debug.DrawRay(transform.position, transform.up * 10, Color.red);

        RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.TransformPoint(Vector2.up));
        var distance = GetDistance(transform.position, hit.collider.transform.position);

        Vector3 endPos = transform.position + (hit.collider.transform.position.normalized * distance);
        lineRenderer.SetPosition(1, endPos);
    }
1

1 Answers

1
votes

To fix the laser jumping around, instead of using the collider's position, you can use the point at which the raycast hits the collider.

RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.TransformPoint(Vector2.up));

if (hit.collider != null && hit.collider.tag == "block")
{
    Vector3 endPos = hit.point;
    lineRenderer.SetPosition(1, endPos);
}

I haven't worked with tilemaps, but according to the unity documentation, the TileMap colliders should work the same as a normal collider.