Rookie
Rookie

Reputation: 193

Unity: How to get the pivot of a game object's sprite?

In unity I'm trying to get the pivot point of the sprite my game object is using.

I changed the sprite's pivot point for it to be easy while I place the game object(Let's call it A) in the game. Now when I try to spawn another object at the transform of A, the new game object , and I know It's hot It's supposed to do, spawns at the top left ofA. I need to somehow calculate the center of the sprite A is using in world coordinates.

I tried this:

Debug.Log(tempGameObj.GetComponent<SpriteRenderer>().sprite.pivot);

But this produces a result as (-80,0,400) while the pivot points are (-0.25, 1.25).

How can I calculate the center?

Upvotes: 3

Views: 5058

Answers (3)

Tomasz Ostafin
Tomasz Ostafin

Reputation: 1

For anyone looking for local pivot of a sprite (aka. custom pivot) it's:

x = _sprite.pivot.x / _sprite.rect.width;

y = _sprite.pivot.y / _sprite.rect.height;

Upvotes: 0

Alex Maker
Alex Maker

Reputation: 1548

You use Sprite.pixelsPerUnit:

spriteRenderer.sprite.pivot / spriteRenderer.sprite.pixelsPerUnit

The currently accepted answer with Camera.ScreenToWorldPoint can accidentally work if you have default Camera values and may fail when you customize the camera plane. It also creates a dependency on a Camera that is, in fact, not needed at all.

Upvotes: 0

Ido Ben Shalom
Ido Ben Shalom

Reputation: 568

what you're looking for is the ScreenToWorldPoint method

Vector3 center = Camera.main.ScreenToWorldPoint(tempGameObj.GetComponent<SpriteRenderer>().sprite.pivot);

Here's the documantation in case you need it https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

Upvotes: 2

Related Questions