jump flappy bird sort of game

Hi. Im making a flappy bird sort of game but when my bird(a cube) crashes to the floor it bounces up and down. Also,I can only jump once. Please tell me what is wrong with this script

using UnityEngine;
using System.Collections;

public class mainscript : MonoBehaviour {



    private int startedjump;
    private float ywhenstarted;


    // Use this for initialization
    void Start () {
   


    }


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

        if (Input.GetMouseButtonDown (0)) {

            ywhenstarted = transform.position.y;
            startedjump = 1;
        }

        if (startedjump == 1) {

            if (transform.position.y >= ywhenstarted + 10) {
               
                startedjump = 0;
               
            }

        }

    }


    void FixedUpdate () {

        transform.position = new Vector2 (transform.position.x + 0.25f, transform.position.y);

        if (startedjump == 1) {

            transform.position = new Vector2 (transform.position.x, transform.position.y + 0.25f);

        }

    }
   
}

:bangbang:

Hey neat — I was helping some middle schoolers last year, and one of them made a “Flappy Cube” project too!

But he did it with physics, which I think is going to be easier than what you’re trying to do here. You’re directly moving the object via its transform, which is also fine, but it means you have to implement all the physics yourself. That’s not super hard in this case, but if you don’t feel you have a good grasp of F = ma, you might want to let Unity handle it for you.

I don’t see anything in this script that would cause your block to ever move down. You only ever move it forward, and sometimes up. So if it’s doing anything else, then you do have physics on it, and now your code is fighting the physics engine (both of you trying to control the transform position), which is certainly going to cause all sorts of problems.

So, look at Rigidbody.MovePosition for the continuous forward movement, and maybe set the velocity to do a jump.

1 Like

I have phyisics for the gravity

and please show a simple example

Those are simple examples- check the bottom of each page. The text description explains what they do, and the code shows how to use it. If you need a full tutorial on using rigidbodies, you should definitely check out this. While you’re at it, watch everything you can stomach in the Learn section- the videos are very informative.

2 Likes

And, in case it wasn’t perfectly clear, if you’re using physics for the gravity you need to use physics for everything. Do not assign to transform.position when using physics. Doing so will only lead to suffering and grief.

1 Like

ok thanks a lot again everyone,this community is being so useful

1 Like