Camera width issue

I’m making so that apple would move to different side when reaches corner of camera view (screen) but this is what happens:
http://server.edgu.lt/ign/2017-08-16_19-33-59.gif

my code:

   if (movingRight) {
			transform.Translate(Vector3.right * Time.deltaTime * 3);
			if ((transform.position.x * 100f) >= (Camera.main.pixelWidth / 2f)) {
				movingRight = false;
			}
		} else {
			transform.Translate(Vector3.left * Time.deltaTime * 3);
			if ((transform.position.x * 100f) <= (-Camera.main.pixelWidth / 2f)) {
				movingRight = true;
			}
		}

Hey Bud!

First you need to know that Transform.Position is not the same as your camera bounds! So you simply need to convert your sprite world position to a screen position. I did it for you!

If it works, please set my reply as the answer then vote for it to :slight_smile:

My pleasure.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Helper1 : MonoBehaviour {

    float spriteWidth;
    bool movingRight = true;
    Vector3 rightBoundPos, leftBoundPos;

    RectTransform myRectTransform;

    public void Start()
    {
        //You need a RectTransform to make the script work!
        myRectTransform = GetComponent<RectTransform>();

        /*
         * If your sprite changes its scale in game, put the next lines in Update!
        */

        //It takes the scale and width of your sprite
        spriteWidth = (myRectTransform.rect.width * transform.localScale.x);

        //It defines the right limit
        rightBoundPos = Camera.main.WorldToScreenPoint(new Vector3((transform.position.x + spriteWidth / 2), transform.position.y, transform.position.z));

        //Then the left limit
        leftBoundPos = Camera.main.WorldToScreenPoint(new Vector3((transform.position.x - spriteWidth / 2), transform.position.y, transform.position.z));
    }

    // Update is called once per frame
    void Update ()
    {
        if (movingRight)
        {
            transform.Translate(Vector3.right * Time.deltaTime * 3);
            
            if (rightBoundPos.x >= Camera.main.pixelWidth)
                movingRight = false;
        }
        else
        {
            transform.Translate(Vector3.left * Time.deltaTime * 3);

            if (leftBoundPos.x <= 0)
                movingRight = true;
        }
    }
}