2
votes

I have a piece of code that is trying to get the player to jump between 2 boxes only Cube 1 (position on left side) and Cube 2 (on right side) by tapping.

The issue with the Move() function is that it starts jumping from Cube 1 to Cube 2, then Cube 2 back to Cube 1, but from this point on, the player jumps from Cube 1 to the left side the opposite of Cube 2.

The jump functions are working, but I think the logic is incorrect.

Move:

void Move(){
    int i = 0;
    while ((isGrounded == true) && (i < 10)) {

        if(atCube1 == true){
            JumpRight();
        }

        if(atCube2 == true){
          JumpLeft();
        }

        i++;
    }
}

OnCollisionEnter:

void OnCollisionEnter (Collision col)
{
    Debug.Log("OnCollisionEnter");


    if (col.gameObject.name == "Cube 1"){
        Debug.Log ("++++++ C U B E 1   H I T ++++++++");

        atCube1 = true;
        isGrounded = true;

    }

    if(col.gameObject.name == "Cube 2"){

        Debug.Log ("Cube 2 hit");
        atCube2 = true;
        isGrounded = true;

    }
}
1
I've fixed your formatting. Two things: 1) you don't need == true . 2) what if atCube1 and atCube2 are both true? - Wai Ha Lee
Does your JumpRight function reset the atCube1 and isGrounded field values? - Neil Cross
Hi @Wai, thanks for responding, I dont think atCube1 and 2 can be true at the same time, as this is in the OnCollisionEnter function, please see it below, void OnCollisionEnter (Collision col) { Debug.Log("OnCollisionEnter"); if (col.gameObject.name == "Cube 1"){ Debug.Log ("++++++ C U B E 1 H I T ++++++++"); atCube1 = true; isGrounded = true; } if(col.gameObject.name == "Cube 2"){ Debug.Log ("Cube 2 hit"); atCube2 = true; isGrounded = true; } } - tony2016
Hi @Neil, No the jump functions do not reset the atCube1 and isGrounded , these values are set to true in the OnCollisionEnter() function. Should they be set to false in the OnCollisionExit() function or else where? Thanks! - tony2016
... You can easily check this by setting atCube2 to false when on cube 1 and atCube1 to false when on cube 2. - Wai Ha Lee

1 Answers

0
votes

You should make atCube1 = false; after it left cube1(do it for cube2 too). Also you can add isGrounded = false; when it does not collides anything.

1-You start at cube1, atCube1 = true

2-Jump to cube2, atCube1 = true, atCube2 = true

3- Jump to cube1 again, it jumps left because still atCube2 = true . In fact, it jumps right at first and then jumps left because of your if statements' order. Just add false values to booleans to fix it.