- Home /
Line Collision Detection for 2D Game
I am developing game related to line drawing in 2d.
At present I can able to draw line using Line Renderer. But I want to detect its collision also but right now I can't able to find any way.
I also used Google for same thing but in that I don't found any useful content related to this.
I don't have any idea related to ray casting in line collision detection. Any way thanks for your suggestion.
use raycast to detect collison and then draw your line upto that,.....
For each segment of line, I have to attach which type of collider?
If you don't want to go down the maths route I have some code from a previous project which creates a collider between two points of a line renderer. If you had a collider on each line you could cast a ray from each line to see if it hit any others:
public float lineWidth = 0.5f;
private GameObject pointB;
private LineRenderer lRenderer;
private BoxCollider col;
void Start(){
if(!(lRenderer = GetComponent<LineRenderer>())){
lRenderer = gameObject.AddComponent<LineRenderer>();
}
// Setup line renderer
lRenderer.SetVertexCount(2);
lRenderer.SetWidth(lineWidth, lineWidth);
// Create point B
pointB = new GameObject("Point B");
//pointB.transform.parent = transform;
pointB.transform.position = Vector3.zero + transform.right * 10;
col = gameObject.AddComponent<BoxCollider>();
}
void Update(){
// Update line renderer positions
lRenderer.SetPosition(0, transform.position);
lRenderer.SetPosition(1, pointB.transform.position);
// make point A (our position) look at point B
Vector3 direction = pointB.transform.position - transform.position;
transform.right = direction.normalized;
// Resize collider to fit line renderer
col.center = Vector3.right * direction.magnitude /2;
col.size = new Vector3(direction.magnitude, 1,1);
}
Answer by amila_15 · Jan 17, 2018 at 02:00 PM
Hello @ siddharth3322 , I search a solution for my own problem. By chance I was directed to your problem. This tutorial will definitely help you. Visit https://www.youtube.com/watch?v=dmBQQ2XtuhU∈dex=72&list=LLYbK_tjZ2OrIZFBvU6CCMiA . If this what you wanted, make this as the answer. It will help others.
@amila thanks for reply but this is really old question, you have answered :) But thank you other users definitely get some outcome from this.