I am making a game on Android where you can draw straight lines, that acts as platforms, here’s the code for this :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineSpawn : MonoBehaviour
{
Vector2 firstPosition;
Vector2 movePosition;
LineRenderer lr;
GameObject line;
public float lineWidth = 5f;
public int lineRoundCorners = 2;
private BoxCollider2D lineCollider;
private Touch touch;
void Start()
{
}
void Update()
{
if (Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
Destroy(line);
lr = null;
firstPosition = Camera.main.ScreenToWorldPoint(touch.position);
movePosition = firstPosition;
line = new GameObject("Platform");
lr = line.AddComponent<LineRenderer>();
lr.enabled = true;
lr.positionCount = 2;
lr.SetPosition(0, firstPosition);
lr.SetPosition(1, firstPosition);
lr.useWorldSpace = true;
lr.numCapVertices = lineRoundCorners;
lr.widthMultiplier = lineWidth;
lr.startColor = Color.green;
lr.endColor = Color.green;
lr.sortingOrder = 1;
lr.material = new Material(Shader.Find("Sprites/Default"));
}
else if (touch.phase == TouchPhase.Moved)
{
movePosition = Camera.main.ScreenToWorldPoint(touch.position);
lr.SetPosition(1, movePosition);
}
else if (touch.phase == TouchPhase.Ended)
{
AddColliderToLine(lr, firstPosition, movePosition);
}
}
}
private void AddColliderToLine(LineRenderer line, Vector2 startPoint, Vector2 endPoint)
{
lineCollider = new GameObject("LineCollider").AddComponent<BoxCollider2D>();
lineCollider.transform.parent = line.transform;
float lineWidth = line.endWidth;
float lineLength = Vector2.Distance(startPoint, endPoint);
lineCollider.size = new Vector2(lineLength, lineWidth);
Vector2 midPoint = (startPoint + endPoint) / 2;
lineCollider.transform.position = midPoint;
float angle = Mathf.Atan2((endPoint.y - startPoint.y), (endPoint.x - startPoint.x));
angle *= Mathf.Rad2Deg;
lineCollider.transform.Rotate(0, 0, angle);
}
}
Now, I wanna add an enemy that you can kill by drawing a line on it, here the code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnnemyScript : MonoBehaviour
{
void Start()
{
}
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("TOUCHING");
}
}
The OnTriggerEnter2D works fine with any other Colliders in my game, but it doesn’t detect the BoxCollider2D LineCollider, even when I can see in Unity that the Collider2D of the ennemy and the line are touching each other. Does anyone have an idea of why this happens ?
Thank you for your help !