1

My sprite moves to the left, as it should but it stops moving and does not go offscreen, as I want it to. It's as if there is an invisible wall.

I have tried https://www.youtube.com/watch?v=YfIOPWuUjn8.

In the video, the person's sprite completely moves off the screen but mine doesn't.

public Sprite Pokemon_0;
public Sprite Pokemon_1; 

void Update()
        {
        if (transform.position.x >= -40) 
        {
            this.gameObject.GetComponent<SpriteRenderer>().sprite = Pokemon_0;
            transform.Translate(-1f,0f,0f);
        }

I am working on the sprite moving off the screen on the left, and a different sprite appearing from the right and moving to the centre of the screen. The code doesn't include anything about the second sprite but that is why I have referred to the sprite in my code.

HSN720
  • 71
  • 2
  • 12

2 Answers2

2

You're telling it to only move left if (transform.position.x >= -40).

So either change your camera so that x = -40 is outside of your screen, or decrease the value in the boolean expression to something lower than -40 so that it moves further left until it stops moving, e.g.:

if (transform.position.x >= -80f) 
{
    transform.Translate(-1f,0f,0f);
}

Also, GetComponent is an expensive procedure, and you only need to set the sprite once, so you should create a Start method that does the sprite assignment. This way, you don't waste time every frame getting the same component and assigning the sprite that's already assigned to it.

The this.gameObject. part is redundant, so you can get rid of that part as well:

Start()
{
    GetComponent<SpriteRenderer>().sprite = Pokemon_0; 
}
Ruzihm
  • 19,749
  • 5
  • 36
  • 48
1

Just adding to Ruzihm's answer, you can also try to use

if (GetComponent<Renderer>().isVisible) 
{
    transform.Translate(-1f,0f,0f);
}

instead of using a number such as "-40f" or "-80f", in this way you can be sure that the sprite will be off screen.

Nícolas
  • 406
  • 3
  • 8
  • 24
  • My understanding is that this may produce unexpected positive results during development if the renderer is in view of the scene editor's camera. – Ruzihm Jul 18 '19 at 18:27