Search code examples
c#unity-game-enginegame-physicsunity3d-2dtools

Unity: Move Sprite Up and Down


While I know my way round C# I am new to using it in game development and Unity. I am wanting to make a ball bounce up and down. I can easily get the ball to move left and right but when change my code from a 'roll' to a 'bounce' I get the below result:(The ball goes diagonally not up and down) enter image description here

but what I want:

enter image description here

// Update is called once per frame
    void Update () {

        if (moveDown) {
            transform.localScale = new Vector3 (-1f, 1f, 1f);
            GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D> ().velocity.x);
        } else {
            transform.localScale = new Vector3 (1f, 1f, 1f);
            GetComponent<Rigidbody2D> ().velocity = new Vector2 (-speed, GetComponent<Rigidbody2D> ().velocity.x);
        }
    }

I'm sure the answer must be something simple but after a long day my brain has gone to mush. Can anyone advise?

Ps the working left to right code goes something like this:

transform.localScale = new Vector3 (-1f, 1f, 1f);
            GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D> ().velocity.y);

Solution

  • A Vector2 has two components; X and Y. The "X" component of the velocity represents the object's horizontal speed (left/right). The "Y" component of the velocity represents the object's vertical speed (up/down).

    To move straight up and down, the "X" component of the velocity must be 'Zero' (0), otherwise the object will continue to move horizontally as well as vertically, resulting in a diagonal.

    When calling the constructor for Vector2, you pass in two parameters; the first parameter is the "X" value, and the second component is the "Y" value. In your example code, you pass a non-zero value in the first (X) parameter, resulting in diagonal movement.