Tuesday, November 19, 2019

Creating custom collision map for 2D


I have a 2D level that I have built in my map editor, and I was wondering the best way to create a collision map for it.


I have a collision map layer in my map editor, which saves each node (for example, a rectangle would be just 0,0 0,50 50,60 0,60)


I was just wondering how I could take my node locations and convert it to a collision map for Unity.



Thanks! I feel this has to be able to be done, I can think of how I would do it in flash... but I am not sure how to manipulate it in Unity.


EDIT PICTURE: So I have a node at each one of these red dots (surrounding my terrain lets say) I want to build a collider from those nodes


nodes collision map



Answer



I thought since these types of questions seem to show up now and then I'd explain myself a bit more in detail.


Assuming you have a 2D level from a heightmap like in the image without any "overhanging" geometry:


What we want to do is check if point p is below the line, in which case we have a collision at l_p. To accomplish this we interpolate v1.Y and v2.Y value to check the height of the line at p.X. If this l_p.Y is larger than p.Y then there is a collision.



  • Start by checking if v1.X <= p.X < v2.X

  • calculate interpolation amount (a), ie, how large part of v1.Y and v2.Y respectively should be used where a = (p.X - v1.X) / (v2.X - v1.X)


  • calculate interpolated Y by y = (1-a) * v1.Y + a * v2.Y

  • if y >= p.Y then there is a collision

  • If needed solve interpenetration by setting p.Y = y

  • IMPORTANT: If you apply an impulse to the body at this point make sure to check that there is actually a closing velocity ie that there is a velocity pointing downwards in this case. Otherwise you might get another collision reported next frame sending the body downwards again.


check if point p is below the line v1-v2


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...