2D Collision Detection
I am trying to implement a method that detects a collision between two objects; a moving cannonball (circle) and a stonehenge (created using line renderer). So far this is my code but the DetectCollision method always returns false and is not detecting collision properly:
public class CollisionDetection : MonoBehaviour { public GameObject cannonBall; public PerlinNoise stoneHenge;
bool istrue;
// Update is called once per frame
void Update()
{
print(DetectCollision(stoneHenge.vp, cannonBall.transform.position));
//stonehenge.vp is an Vector3D[] containing vertices of lines that create the stone henge
}
private bool DetectCollision(Vector3[] target, Vector2 obj)
{
for (int i = 0; i < target.Length; i++)
{
//collision detected when the distance between one of the point of stonehenge and the
cannonball <=0.0f
if (Vector2.Distance(target[i], obj) <= 0.0f)
{
istrue = true;
break;
}
else
{
istrue = false;
break;
}
}
return istrue;
}
}
Answer by ChuckIes · Oct 22, 2019 at 10:20 PM
Your distance check will only return true when the target and the object have the exact same transform position. You likely want something like Physics.OverlapBox() or Physics2D.OverlapBox().
Your answer
Follow this Question
Related Questions
OnCollisionEnter() from non monobehaviour script 1 Answer
Collision detection 1 Answer
DoubleJump 1 Answer
Objects move a fraction of the way through controller collider every time 0 Answers
Raycast on moving object? 2 Answers