0
\$\begingroup\$

I'm drawing some kind of bullet trace effect with LineRenderer in my 2D Game Project with Unity. At some position, setting position of LineRender result weird:

enter image description here

In the above screenshot, you can see two types of lines are exists. Pure red lines are result of Debug.DrawRay which is only renders in Scene view, not actual game play, and another lines which has yellow to red gradient are actual line renders I want to draw.

I used exactly same code for rendering both two, Debug.DrawRay() and LineRenderer.SetPosition(), but as you can see only DrawRay works as I expected and LineRenderers are cutted and pointing wrong direction.

Here's the code I'm trying:

void Fire() {
    Vector3 shootDirection = m_ShootPoint.right;

    RaycastHit2D hit = Physics2D.Raycast(m_ShootPoint.position, shootDirection, m_Range);
    Debug.DrawRay(m_ShootPoint.position, shootDirection.normalized * m_Range, Color.red, 20);

    // On Hit, set end position where it hits
    if (hit) {
        CreateBulletTrace(m_ShootPoint.position, hit.point);
    }
    // Otherwise, render straight until it's range
    else {
        CreateBulletTrace(m_ShootPoint.position, shootDirection.normalized * m_Range);
    }
}

void CreateBulletTrace(Vector3 startPos, Vector3 endPos) {
    GameObject bulletTraceObj = Instantiate(m_BulletTraceLineRendererPrefab);
    LineRenderer bulletTraceLineRenderer = bulletTraceObj.GetComponent<LineRenderer>();
    bulletTraceLineRenderer.useWorldSpace = true;

    bulletTraceLineRenderer.SetPosition(0, startPos);
    bulletTraceLineRenderer.SetPosition(1, endPos);

    // Destroy(bulletTraceObj, 0.1f);
}

Note that LineRenderer checked use world space to true. What am I missing?

Using Unity 2019.1.0f2.

\$\endgroup\$
1
\$\begingroup\$

The second argument in DrawRay is an offset.

The argument you provide to a LineRenderer is a position.

shootDirection.normailized * m_Range is an offset from zero — you want to add your start point to get an absolute position.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.