How to keep sprite on screen while increasing its width to screen width

How to keep sprite on screen while increasing its width to screen width

I have been able to increase the width of a sprite to the width of the screen size, but the sprite exceeds the borders of the screen width to the right or left when I try expanding it when it's not at the center. How can I scale the sprite in such a way that it's width increases on both sides till it occupies the screen width without exceeding it's bounds, regardless of the sprite's initial position? Please see my code below:
bool isScaling = false;

IEnumerator scaleToX(SpriteRenderer spriteToScale, float newXValue, float byTime)
       if (isScaling)
           yield break;
       isScaling = true;

       float counter = 0;
       float currentX = spriteToScale.transform.localScale.x;
       float yAxis = spriteToScale.transform.localScale.y;
       float ZAxis = spriteToScale.transform.localScale.z;

       while (counter < byTime)
          counter += Time.deltaTime;
          Vector3 tempVector = new Vector3(currentX, yAxis, ZAxis);
          tempVector.x = Mathf.Lerp(currentX, newXValue, counter / byTime);
          spriteToScale.transform.localScale = tempVector;
          yield return null;

       isScaling = false;


Answer 1:

This is actually very simple. All you need to do is determine the Camera Bounds, and then set the final resting position of your sprite, based on these bounds.

So, you would have the start position and size -- Determine the end position and size that you want, then lerp to it. It is that easy.

Here is the script that will do this:

using UnityEngine;
using System.Collections;

public class Square : MonoBehaviour {

    Bounds CameraBounds;

    Vector2 EndScale;
    Vector2 EndPosition;
    Vector2 StartScale;
    Vector2 StartPosition;

    float Speed = 2;
    float SPEED = 2;

    void Start () {

        CameraBounds = GetCameraBounds ();

        StartPosition = this.transform.position;
        StartScale = this.transform.localScale;

        EndScale = CameraBounds.size;
        EndPosition =;

    void Update () {

        Speed -= Time.deltaTime;
        if (Speed <= 0)
            Speed = 0;

        this.transform.localScale = Vector2.Lerp (EndScale, StartScale, Speed/SPEED);
        this.transform.position = Vector2.Lerp (EndPosition, StartPosition, Speed / SPEED); 

    public Bounds GetCameraBounds()
        float screenAspect = (float)Screen.width / (float)Screen.height;
        float cameraHeight = Camera.main.orthographicSize * 2;
        Bounds bounds = new Bounds(Camera.main.transform.position,new Vector3(cameraHeight * screenAspect, cameraHeight, 0));
        return bounds;


And this is an example of this script running on a 1:1 ratio sprite:
enter image description here