I´m tryng to make a game with drawing lines, with one question, the line can not cross it self.
I´m using vectrosity but i can not assign a collider to the Game Object Vector Drawnline.
Is there any chance to assign a collider to the lines or anybody now how can i do that??
You can add a collider to a line by setting the ‘collider’ property to ‘true’.
// Create the line's points.
Vector2 lineStart = new Vector2(10, 10);
Vector2 lineEnd = new Vector2(20, 20);
// The line's width.
int width = 5;
// Create the line object.
VectorLine line = new VectorLine("SuperLine", new Vector2[] { lineStart, lineEnd }, null, width);
// Add a collider.
line.collider = true;
// Draw the line
line.Draw();
When drawing the next part of the line, you can detect collisions with the existing part by using ‘Physics2D.Raycast’.
// Create the 2nd line's points.
Vector2 line2Start = new Vector2(0, 0);
Vector2 line2End = new Vector2(45, 26);
// Calculate the new line's direction.
Vector2 direction = line2End - line2Start;
direction.Normalize();
// Raycast along the line to see if it hits anything.
RaycastHit2D hit = Physics2D.Raycast(line2Start, direction);
if (hit.collider == null) {
// Didn't hit anything so draw the line.
VectorLine line2 = new VectorLine("MegaLine", new Vector2[] { line2Start, line2End }, null, width);
line2.Draw();
}
Instead of using lines, you can use cubes with very small scale in x & z axis, so they appear like lines but then a box collider will work.
Create a prefab of a cube, leave the scale 1,1,1, and add a box collider. Then when you want to draw a line from point A to point B you would use the following method (give it the prefab of the cube, the start and end position, and the width you want the line to have):
public void DrawLine(Transform linePrefab, Vector3 from, Vector3 to, float lineWidth) {
framesWithoutFiring = 0;
// calculate vector from point A to point B
Vector3 lineVector = to - from;
// instantiate line
Transform lineInstance = GameObject.Instantiate(linePrefab);
// set position of line instance to center of line
lineInstance.position = from + (lineVector / 2f);
// set rotation of line instance so that it's Y axis is from point A to point B
lineInstance.transform.up = toTarget.normalized;
// set length of line instance
lineInstance.transform.localScale = new Vector3(lineWidth, lineVector.magnitude, lineWidth);
}