Hello so I have a script that clamps my sprite from going off screen but only in the middle of the sprite I would like my whole sprite to stay inbounds. I’ve tried to look up solutions but couldn’t find any that fits best for my game or this script
I don’t really understand your code, but if your pivot is in the middle of the sprite then that’s where you set your transforms position… have you thought about maybe counting in the margin from the middle of the sprite to the border of the sprite. (when you clamp…) I’d do a custom clamping if I were you… simple, just do:
if (transform.position.x+margin > screenWidth)
transform.x = screenWidth-margin;
etc
What you need to do is take into account the extents of your sprite and add that value to the clamping limits. To get that information you will need a reference to the sprite renderer you’re using. Here’s how you do it:
//Assumptions I'm doing about your setup
// 1) Somewhere else in your code you're changing the sprite position since
// all you're doing in the code you've shown is clamping
// 2) You're on a 2D game meaning you're using an orthographic camera, not a perspective one
// 3) Your camera does not move in the game, is looking at 0,0,0 from position 0,0,-10
// and is not rotated. (Basically, it has the default values when you make a new scene)
//Define a sprite renderer field and assign it through the inspector
public SpriteRenderer sprRnd;
void Update(){
//Transform sprite extents to viewport space
Vector3 sprVpExtents = cam.WorldToViewportPoint(sprRnd.bounds.extents);
Vector3 pos = cam.WorldToViewportPoint(transform.position);
pos .x = Mathf.Clamp(clampPos.x,sprVpExtents .x - 0.5f,1f-sprVpExtents .x + 0.5f);
pos .y = Mathf.Clamp(clampPos.y,sprVpExtents .y - 0.5f,1f-sprVpExtents .y + 0.5f);
transform.position = cam.ViewportToWorldPoint(pos );
}
And there you have it. Keep in mind this only works if the assumptions I wrote are true. Adjust this if your case demands it.
You could also do this using world space calculations instead of viewport space, which in my opinion, is much more readable and understandable. Like this: