- Home /
top right corner sprite position in screenspace(or worldspace)
Hi, I need to get the screenspace(or worldspace, it does not matter) position of top right corner of a sprite. How can this be done via script?
Answer by robertbu · Feb 20, 2014 at 08:49 PM
I could only find a pretty ugly solution. As with a lot of things dealing with Sprites, what should be easy is difficult or impossible. I'm hoping someone with more experience or knowledge of sprites can come up with something better.
The following code calculates the localTopRight in Start(). Then in Update() it places a small sphere at that location. If you are not going to be scaling or rotating your sprite, you can simplify this code greatly. Most of the complications are in dealing with rotation and scaling.
#pragma strict
private var go : GameObject;
private var localTopRight : Vector3;
function Start () {
var q = transform.rotation;
transform.rotation = Quaternion.identity;
var bounds = GetComponent(SpriteRenderer).bounds;
localTopRight = Vector3(bounds.extents.x, bounds.extents.y, 0.0) + transform.position;
localTopRight = transform.InverseTransformPoint(localTopRight);
transform.rotation = q;
go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
go.transform.localScale = Vector3(0.1, 0.1, 0.1);
}
function Update () {
go.transform.position = transform.TransformPoint(localTopRight);
}
@robertbu ,thanks for helping. can I go with 11 number's localTopRight in your code? Here I am converting it to local and then worldspace back again. Why do we do this? Is it for scale issues? Also can we not write like: transform.rotation=Quaternion.identity? In s$$anonymous$$d of storing it to temporary variable?
Let me explain a bit about this code. What I want to get is the local corner so that if the object is rotated or scaled, I can find the world corner. SprinteRenderer.bounds is an axis aligned and in world coordinates. And when I start the script, I have no idea what angle the sprite will be. Imagine the sprite is rotated at 45 degrees,. The angle-aligned bounds will be much larger than if the rotation is 0.0.
So what I do is save the current rotation and then set the rotation to (0,0,0). This allows me to grab the world corner of the the unrotated object. But at a later time, the object may change scale or be rotated, so I convert the world coordinate into a local coordinate. This gives me a value I can use at some future time that will correctly find the corner no matter how the scale changes or how the rotation changes.
If your sprite is not scaled nor rotated, and you want the corner for this sprite, you can just do:
var bounds = GetComponent(SpriteRenderer).bounds;
var worldTopRight = Vector3(bounds.extents.x, bounds.extents.y, 0.0) + transform.position;
@robertbu, thank you very much. I really appreciate it. Now it looks clear to me.