Skip to main content
added 93 characters in body
Source Link
S.C.
  • 252
  • 1
  • 4

As you may have noticed, the Update function is executed every frame as long as the MonoBehaviour is enabled. You can assign a constant velocity to the Rigidbody of the square instance in the Update function, so it moves at a constant velocity every frame.

if (grounded) {
    if (Input.GetKeyDown(KeyCode.Space)) {
        rigidbody2D.AddForce(new Vector2(0, jumpForce));
    } else {
        rigidbody2D.velocity = new Vector2(2, 0);
    }
}

UPDATE

Savlon's comment,

  • Use FixedUpdate when dealing with Rigidbody.

As you may have noticed, the Update function is executed every frame as long as the MonoBehaviour is enabled. You can assign a constant velocity to the Rigidbody of the square instance in the Update function, so it moves at a constant velocity every frame.

if (grounded) {
    if (Input.GetKeyDown(KeyCode.Space)) {
        rigidbody2D.AddForce(new Vector2(0, jumpForce));
    } else {
        rigidbody2D.velocity = new Vector2(2, 0);
    }
}

As you may have noticed, the Update function is executed every frame as long as the MonoBehaviour is enabled. You can assign a constant velocity to the Rigidbody of the square instance in the Update function, so it moves at a constant velocity every frame.

if (grounded) {
    if (Input.GetKeyDown(KeyCode.Space)) {
        rigidbody2D.AddForce(new Vector2(0, jumpForce));
    } else {
        rigidbody2D.velocity = new Vector2(2, 0);
    }
}

UPDATE

Savlon's comment,

  • Use FixedUpdate when dealing with Rigidbody.
Source Link
S.C.
  • 252
  • 1
  • 4

As you may have noticed, the Update function is executed every frame as long as the MonoBehaviour is enabled. You can assign a constant velocity to the Rigidbody of the square instance in the Update function, so it moves at a constant velocity every frame.

if (grounded) {
    if (Input.GetKeyDown(KeyCode.Space)) {
        rigidbody2D.AddForce(new Vector2(0, jumpForce));
    } else {
        rigidbody2D.velocity = new Vector2(2, 0);
    }
}