- Home /
Question by
UBrownie · Oct 27, 2020 at 11:15 AM ·
triggercollision detectioncollider2dlinedraw
Draw line within bounds of circular collider
Hello all!
I'm trying to draw a line within bounds of a circular object. I found some code online to draw line and with some edit I was able to limit the size of the line.
private Vector3 pos1;
private Vector3 pos2;
public float objectHeight = 1.0f;
public GameObject prefab;
private GameObject go;
private bool isBeingDrawn = false;
private Collider2D collider2d;
private void Start()
{
collider2d = GetComponent<Collider2D>();
}
private void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
pos1 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos1.z = -2f;
pos2 = pos1;
go = Instantiate(prefab, pos1, Quaternion.identity, GameObject.Find("empty").transform);
Vector3 temp = go.transform.localScale;
temp.y = 0.0f;
go.transform.localScale = temp;
isBeingDrawn = true;
}
}
private void OnMouseUp()
{
isBeingDrawn = false;
}
void Update()
{
if (isBeingDrawn)
{
Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (pos.x < collider2d.bounds.extents.x && pos.y < collider2d.bounds.extents.y && pos.x > -collider2d.bounds.extents.x && pos.y > -collider2d.bounds.extents.y)
{
pos2 = pos;
pos2.z = -2f;
}
}
if (pos2 != pos1)
{
Vector3 v3 = pos2 - pos1;
go.transform.position = pos1 + (v3) / 2.0f;
go.transform.localScale = new Vector2(go.transform.localScale.x, v3.magnitude);
go.transform.rotation = Quaternion.FromToRotation(Vector2.up, v3);
}
}
But the line still moves outside the circular object specially at the corners as you can see in the pictures.
How can I keep it within the collider bounds? any help is appreciated.
Comment
Your answer
Follow this Question
Related Questions
Setting a Prefab Clone as the Child of another Object on Collision (2D) 1 Answer
Can more than one colliders be used for different purposes..???? 1 Answer
What other reasons would a 2D collider not make contact with another 1 Answer
Gameobject not detecting collison from other Box Collider 2D [SOLVED?] 2 Answers
Free script/plugin for drawing a line with a collider? 2 Answers