- Home /
Question by
chetan-rane · Mar 17, 2015 at 07:19 AM ·
unity 5javascriptunity 4unity4.6
[closed]how to match boxcollider2d size with image after preserv aspect?
Hi All,
How could i resize the boxcollider2d to match with the image rect after preserv aspect is enable?
rectTransform.rect of image returning whole rectagle, but i want the width and height of image after resizing.
Comment
Best Answer
Answer by chetan-rane · Mar 30, 2015 at 10:21 AM
I found my answer:
Hope anyone interested would get this help
void SetBoxCollider()
{
RectTransform itemRectTransform = this.gameObject.GetComponent<RectTransform>();
// strech box collider
BoxCollider2D itemBoxCollider2D = itemRectTransform.gameObject.GetComponent<BoxCollider2D>();
if (itemBoxCollider2D != null)
{
Image image = itemRectTransform.gameObject.GetComponent<Image>();
if (image.preserveAspect) {
var originalW = (int)(image.sprite.rect.width);
var originalH = (int)(image.sprite.rect.height);
var currentW = image.rectTransform.rect.width;
var currentH = image.rectTransform.rect.height;
var ratio = Mathf.Min (currentW / originalW, currentH / originalH);
var newW = image.sprite.rect.width * ratio;
var newH = image.sprite.rect.height * ratio;
itemBoxCollider2D.size = new Vector2 (newW, newH);
} else {
itemBoxCollider2D.size = image.rectTransform.rect.size;
}
}
}
screen-shot-2015-03-30-at-35615-pm.png
(12.9 kB)
Answer by sensotec · Sep 14, 2016 at 12:34 PM
Working solution!
THANK YOU SO MUCH! Have been looking for a solution to my problem for ages. Decided to tackle it today. And I'm happy I came across your post because it actually works!
Been wasting my time with collider.bounds and rendered.bounds to no avail.
Tkx again!