So I was making an android game in unity3d. I wrote a script to draw straight lines with touch what I do is I first create a gameobject named temp and add line renderer to it and give the line renderer properties. Then I create a collider gameobject , parent it to the line and change its dimensions to the dimension of the line. What I am trying to do is add two colliders one while the line is being moved i.e "touch.phase == TouchPhase.Moved" and delete this collider and add another collider when "touch.phase == TouchPhase.Ended". For some weird reasons I am not able to delete the first collider.
Here is my code
void Update()
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
temp = new GameObject();
temp.AddComponent<LineRenderer>();
temp.layer = LayerMask.NameToLayer("lines");
lr = temp.GetComponent<LineRenderer>();
lr.positionCount = 2;
lr.SetWidth(0.2f, 0.2f);
lr.material = new Material(Shader.Find("Sprites/Default"));
lr.SetColors(Color.black, Color.black);
temp.transform.position = camera.ScreenToWorldPoint(touch.position) + camOffset;
fingerUp = camera.ScreenToWorldPoint(touch.position)+camOffset;
lr.useWorldSpace = true;
spawnCollider = false;
}
//Detects Swipe while finger is still moving
if (touch.phase == TouchPhase.Moved)
{
lr.SetPosition(0, fingerUp);
fingerDown = camera.ScreenToWorldPoint(touch.position)+camOffset;
lr.SetPosition(1,fingerDown);
spawnCollider = true;
lastLine = temp;
// The first collider temporary one
BoxCollider2D col1 = new GameObject().AddComponent<BoxCollider2D>();
col1.transform.parent = temp.transform;
float lineLength = Vector2.Distance(fingerUp, fingerDown);
col1.size = new Vector2(lineLength, 0.2f);
Vector2 midPoint = (fingerUp + fingerDown) / 2;
col1.transform.position = midPoint;
float angle = (Mathf.Abs(fingerDown.y - fingerUp.y) / Mathf.Abs(fingerDown.x - fingerUp.x));
if ((fingerUp.y < fingerDown.y && fingerUp.x > fingerDown.x) || (fingerDown.y < fingerUp.y && fingerDown.x > fingerUp.x))
{
angle *= -1;
}
angle = Mathf.Rad2Deg * Mathf.Atan(angle);
col1.transform.Rotate(0, 0, angle);
}
if (touch.phase == TouchPhase.Ended)
{
if (spawnCollider == true)
{
Destroy(col1); // Deleting the first collider
// Adding the final collider
BoxCollider2D col = new GameObject("Collider").AddComponent<BoxCollider2D>();
col.transform.parent = temp.transform;
float lineLength = Vector2.Distance(fingerUp, fingerDown);
col.size = new Vector2(lineLength, 0.2f);
Vector2 midPoint = (fingerUp + fingerDown) / 2;
col.transform.position = midPoint;
float angle = (Mathf.Abs(fingerDown.y - fingerUp.y) / Mathf.Abs(fingerDown.x - fingerUp.x));
if ((fingerUp.y < fingerDown.y && fingerUp.x > fingerDown.x) || (fingerDown.y < fingerUp.y && fingerDown.x > fingerUp.x))
{
angle *= -1;
}
angle = Mathf.Rad2Deg * Mathf.Atan(angle);
col.transform.Rotate(0, 0, angle);
}
}
}
}
I have added comments where I am doing what.