So I’m building a 2D platformer and I’m at a blockage trying to get one of my weapon types to work. It’s supposed to be like shooting lightning. It makes a beam that splits into two beams that split again, rinse repeat until the max range is hit. I’m having trouble drawing the beams.
What my code does is it uses a linecast to see if it hits anything. If it does, it sets ‘lineEnd’ to the point where it hit. If not, ‘lineEnd’ stays the same random point. The sprite is set to the center point of the line and scaled to be the distance of the line. What I need now is to find the angle of my linecast so the sprite rotation can be set. Otherwise, it just looks like a horizontal line that’s been slightly shifted.
//Object to instantiate
public GameObject nextshot;
//Beam collider
Collider2D beam;
//Linecast positions
Vector2 lineStart;
Vector2 lineEnd;
// Use this for initialization
void Start () {
//Set segment angle and distance
lineStart = transform.position;
lineEnd.x = lineStart.x + Random.Range(10f, 15f);
lineEnd.y = lineStart.y + Random.Range(-10f, 10f);
makeBeam();
}
//Linecast to find hits and call function to draw beam
void makeBeam ()
{
RaycastHit2D hit = Physics2D.Linecast(lineStart, lineEnd);
if (hit.collider != null)
{
lineEnd = hit.point;
}
drawBeam(lineStart, lineEnd);
}
//Draw the beam
void drawBeam (Vector2 a, Vector2 b)
{
Debug.DrawLine(lineStart, lineEnd);
transform.position = a + (b - a) * 0.5f;
float dist = Vector2.Distance(a, b);
transform.localScale = new Vector2(dist + 1, 1);
}
}
I need to find the rotation angle of the line that goes between points ‘lineStart’ and ‘lineEnd’ so that I can set the rotation of my sprite.