Sultan ul Arefin
Sultan ul Arefin

Reputation: 37

How can I stop my character Going Up Automatically?

Why my character going up automatically though I'm not pressing any button? I want to control my player jump movement. But I cant do it. What is the solution? Please explain. Can you also suggest how can I customise my jump, like jump twice? etc

public class movement: MonoBehaviour {
  public float speed = 10;

  private Rigidbody2D rb;

  public float jumpSpeed = 1;

  void Start() {
    rb = GetComponent < Rigidbody2D > ();
  }

  // Update is called once per frame
  void Update() {
    Jump();
    var inputX = Input.GetAxis("Horizontal");
    Vector3 movement = new Vector3(inputX, 0, 0) * speed;
    movement *= Time.deltaTime;
    transform.Translate(movement);

    Vector3 characterScale = transform.localScale;
    if (inputX < 0) {
      transform.localScale = new Vector3(5, transform.localScale.y, transform.localScale.z);
    }

    if (inputX > 0) {
      transform.localScale = new Vector3(-5, transform.localScale.y, transform.localScale.z);
    }
  }

  void Jump() {
    if (Input.GetKeyDown(KeyCode.Space));
    rb.velocity = Vector2.up * jumpSpeed;
  }
}

Upvotes: 0

Views: 67

Answers (1)

Kaia
Kaia

Reputation: 893

Your issue is with the if statement in Jump. If there are no curly braces after an if statement, only the first statement is enclosed within the if.

if (something)
    do_stuff(); // This will execute if something evaluates to true
    do_other_stuff(); // This will execute no matter what

In your case, the next statement looks like this:

if (Input.GetKeyDown(KeyCode.Space))
    ;

The semicolon is an empty statement. Then, the second line rb.velocity = Vector2.up * jumpSpeed; executes normally.

This is in java, but the same logic applies to C#

Proper code will look like:

if (Input.GetKeyDown(KeyCode.Space)) {
    rb.velocity = Vector2.up * jumpSpeed;
}

Note that there is no semicolon on the line of the if statement.

Upvotes: 2

Related Questions