[Question] More consistent way of Padding?

The Message “Better way to set up “padding”” makes lot of sense, and can vary with your sprite size, which I think is great. My first thought upon completing the lesson, though, was that if we’re using Camera.ViewportToWorldPoint so we could clamp the limits in world space, shouldn’t we define padding in world space values, as well, not screen space values?

Thanks for replies on why or why not to do that.

That seems like a sensible suggestion. That way everything would be consistent that way. I guess if you wanted the visual padding space to be constant no mater what scale the game had you might want the other way.

Hi,
Another way is to use a Unity builtin function: (I’m using version 5 so I must get the Renderer component this way)

minX = leftMost.x + GetComponent().bounds.extents.x;

Bounds = “…is a box aligned with coordinate axes and fully enclosing some object…”

extents = “The extents of the box. This is always half of the size.”

Hope someone finds this helpful.

Cheers

2 Likes

hey i want to use this code however i cant find a answer on the internet as to a further explanation behind
extents.
i get bounds is the box that encloses the object, however i don’t get extents and what it means by always half of the size?
thanks in advance.

If the box encloses the object, from the center of the box to its limits is
half the size of the box.

Maple Moose gamedev@discoursemail.com escreveu no dia quarta, 1/02/2017
às 04:24:

I did it this way.
Get the SpriteRenderer
From this, get the bounds of the player sprite.
Add the x bounds to minX, subtract from maxX and the sprite goes to the edge.

It may be you want to add a small amount of additional padding (probably 0.05f would do)

I actually stopped the video before he got to the padding value because I didn’t like the sprite going off the screen. I came up with a solution that is dependent on pixels per unit of your sprite, but will scale if you import a different sprite.

void Start () {
	float distance = transform.position.z - Camera.main.transform.position.z;	
	Vector3 leftmost = Camera.main.ViewportToWorldPoint (new Vector3 (0, 0, distance));
	Vector3 rightmost = Camera.main.ViewportToWorldPoint (new Vector3 (1, 0, distance));
	Vector3 sprite_size = GetComponent<SpriteRenderer> ().sprite.rect.size;

	float halfsize = sprite_size.x * .5f * .01f;

	xmin = leftmost.x + halfsize;
	xmax = rightmost.x - halfsize;
}

This is EXACTLY what I was looking for and works perfectly no matter the Pixels Per Unit or size of the sprite! Awesome!