Search Unity

2D / Animate Segments of LineRenderer with Sprite Sheets and Correct Resolution

Discussion in 'Editor & General Support' started by alecmaro, Nov 7, 2020.

  1. alecmaro

    alecmaro

    Joined:
    Oct 11, 2020
    Posts:
    2
    I have a laser gun in my 2D game that works well but the line renderer is giving me trouble. The sprite sheet I'm using gets skewed when the gun shoots and I want the segments of the line to play an animation rather than a still image. I believe I have all of the assets and code to accomplish this, but I am obviously missing something.

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class AnimatedTexture : MonoBehaviour
    7. {
    8.     private float iX = 0;
    9.     private float iY = 1;
    10.     public int _uvTieX = 1;
    11.     public int _uvTieY = 1;
    12.     public int _fps = 10;
    13.     private Vector2 _size;
    14.     private LineRenderer _myRenderer;
    15.     private int _lastIndex = -1;
    16.  
    17.     void Start()
    18.     {
    19.         _size = new Vector2(1.0f / _uvTieX,
    20.                              1.0f / _uvTieY);
    21.  
    22.         _myRenderer = GetComponent<LineRenderer>();
    23.  
    24.         if (_myRenderer == null) enabled = false;
    25.  
    26.         _myRenderer.material.SetTextureScale("_MainTex", _size);
    27.     }
    28.  
    29.  
    30.  
    31.     void Update()
    32.     {
    33.         int index = (int)(Time.timeSinceLevelLoad * _fps) % (_uvTieX * _uvTieY);
    34.  
    35.         if (index != _lastIndex)
    36.         {
    37.             Vector2 offset = new Vector2(iX * _size.x,
    38.                                          1 - (_size.y * iY));
    39.             iX++;
    40.             if (iX / _uvTieX == 1)
    41.             {
    42.                 if (_uvTieY != 1) iY++;
    43.                 iX = 0;
    44.                 if (iY / _uvTieY == 1)
    45.                 {
    46.                     iY = 1;
    47.                 }
    48.             }
    49.  
    50.             _myRenderer.material.SetTextureOffset("_MainTex", offset);
    51.  
    52.  
    53.             _lastIndex = index;
    54.         }
    55.     }
    56. }
    Line Renderer Inspector
    lineRenderIns.png lineSkew.png skewed line when shot shockMatIns.png shockProper.png proper sprite size shockShader.png
     
  2. alecmaro

    alecmaro

    Joined:
    Oct 11, 2020
    Posts:
    2
    I also wanted to share the sprite sheet I'm using and mention that the code is intended to build a sprite sheet out of the material and then display the images in order in each segment of the line rendered when laser is shot. spriteEditor.png