- Home /
Move sprite depending on its collider position
Hi everyone, i'm having a little problem trying to accomplish this:
I have a simple rectangular sprite with a BoxCollider2D attached to it. The box collider size is smaller than the whole sprite and its center is different from the sprite's center. [I have a sprite of a man, with the box collider just around his feet]
What i want to do is to transform the sprite's position when it its a trigger, and move it to another linked trigger. It works fine if i use
player.transform.position = new Vector3 (xScenePosition, yScenePosition)
where xScenePosition and yScenePosition are the linked trigger coordinates. But this centers the whole sprite on the linked trigger, instead i need to have its BoxCollider2D centered on the linked trigger position.
It should work if i get the sprite.transform.position
and make the difference with its collider center position. Then i can add this calculated difference to the resulting linked trigger position.
i've tried getting Collider.center
but i know it gives some local coordinates and i don't know how to translate them to get the right difference to get this working.
Does anybody have an advice for this?
Thank you very much
Answer by robertbu · Feb 18, 2014 at 05:42 PM
If you don't have any rotation in the sprite, you can do it this way:
var offset = player.GetComponent(BoxCollider).center;
player.transform.position = new Vector3 (xScenePosition, yScenePosition) - offset;
If your sprite rotates, this will work:
var offset = player.GetComponent(BoxCollider).center;
player.transform.position = new Vector3 (xScenePosition, yScenePosition) + player.transform.position - playertransform.TransformPoint(offset);
i've tried that before, but for some reason the collider doesn't get in the middle of the trigger :( maybe that's because it's "center" position is in some local scale but i don't know how to convert it