- Home /
Find point of top of rotated sprite
So, I have this object that 'orbits' around a planet object. I need to determine if the top of the object is closer to the epicentre of the planet or if the bottom of the object is closer. I have the following code, however it is simply not working:
Bounds theBounds = spriteRenderer.bounds;
//float angle = transform.rotation.eulerAngles.z;
float angle = Mathf.Deg2Rad*transform.rotation.eulerAngles.z;
Vector2 topBus = new Vector2(transform.position.x * Mathf.Cos(angle), transform.position.y+theBounds.extents.y * Mathf.Sin(angle));
Vector2 bottomBus = new Vector2(transform.position.x * Mathf.Cos(angle), transform.position.y-theBounds.extents.y * Mathf.Sin(angle));
if(Vector2.Distance(topBus,planet.transform.position) < Vector2.Distance(bottomBus,planet.transform.position))
{
rotationDirection = -90;
}
else
{
rotationDirection = 90;
}
I am completely stumped over why this is not working. I was wondering if I could get a pointer over what's wrong or alternative code that would work.
Thanks a lot!
Answer by ugriffin · Oct 14, 2016 at 11:17 AM
I have found a solution to my problem after a great deal of Google searching. There was a mistake in the formula used to calculate the actual points.
The correct code is:
//Class to hold the function in for simplicity´s sake.
public class SpriteTools
{
//float angle: the angle of rotation (if any) for our sprite.
//Vector 2 pivot: the pivot from which the sprite is rotating (usually the transform)
//Vector2 point: the point (using relative sprite x and y) that we wish to calculate.
public static Vector2 returnWorldSpacePointFromSprite(Vector2 pivot,Vector2 point,float angle = 0.0f)
{
return new Vector2((point.x - pivot.x) * Mathf.Cos(angle) - (point.y - pivot.y) * Mathf.Sin(angle) + pivot.x,(point.y - pivot.y) * Mathf.Cos(angle) + (point.x - pivot.x) * Mathf.Sin(angle) + pivot.y);
}
}
Example usage:
Bounds theBounds = spriteRenderer.bounds;
float angle = Mathf.Deg2Rad*transform.rotation.eulerAngles.z;
Vector2 topBus = SpriteTools.returnWorldSpacePointFromSprite((Vector2)transform.position,new Vector2(transform.position.x,transform.position.y+theBounds.extents.y),angle);
Vector2 bottomBus = SpriteTools.returnWorldSpacePointFromSprite((Vector2)transform.position,new Vector2(transform.position.x,transform.position.y-theBounds.extents.y),angle);
if(Vector2.Distance(topBus,planet.transform.position) > Vector2.Distance(bottomBus,planet.transform.position))
{
rotationDirection = -90;
}
else
{
rotationDirection = 90;
}
Do note that this code won't account for sprites that are scaled up or down but it can be easily modified to do so.
Your answer
Follow this Question
Related Questions
Question on Sprite and Movement 0 Answers
Texturing custom 2d sprite 0 Answers
Handling Multiple Resolutions in 2D? 0 Answers
In-Game 2D Sprite Building System 0 Answers
Top Down Sprite Facing Mouse 2 Answers