- Home /
Collider sometimes fails to detect clicks
I have a script set up that creates a line with a LineRenderer and detects clicks with a CapsuleCollider that is aligned with the line. You are supposed to be able to click the line at any point, and drag its endpoint to a new position.
The problem is that, while it works most of the time, sometimes it seems that the collider stops registering clicks in the correct place, so the line can't be moved. I end up having to "find" the collider by clicking around until I hit it. It seems to often (but not not always) be easier to hit when I click near the middle of the line. Other times it's off to the side.
As far as I can tell it is not a case of the collider being misaligned, because I can see it lining up in the scene view.
What am I doing wrong?
public class ResizeLine : MonoBehaviour {
public Vector3 startPoint;
public Vector3 endPoint;
CapsuleCollider capsule;
LineRenderer line;
float width = 2f;
void Start () {
line = gameObject.AddComponent("LineRenderer") as LineRenderer;
line.SetWidth(width*0.2f,width);
line.SetPosition(0,startPoint);
line.SetPosition(1,endPoint);
capsule = gameObject.AddComponent("CapsuleCollider") as CapsuleCollider;
capsule.radius = width*0.5f;
capsule.height = 2f;
capsule.direction = 2;
capsule.center = Vector3.zero;
endPoint = startPoint;
endPoint.x = 20;
Resize(endPoint);
}
void Resize(Vector3 newEndPoint)
{
endPoint = newEndPoint;
endPoint.z = startPoint.z;
line.SetPosition(1,endPoint);
transform.position = startPoint + (startPoint + endPoint)/2;
capsule.height = Vector3.Distance(startPoint,endPoint);
capsule.transform.LookAt(startPoint);
}
void OnMouseDrag()
{
var mousePos = Camera.main.ScreenToWorldPoint( Input.mousePosition );
Resize (mousePos);
}
void OnMouseDown()
{
Debug.Log("click");
var mousePos = Camera.main.ScreenToWorldPoint( Input.mousePosition );
Resize (mousePos);
}
}