Search code examples
c#unity3d-2dtools

GameObject doesn't jump on adding force to rigidbody


I try to make character jump on adding force

public class DemonController : MonoBehaviour
{
 [SerializeField]
 private float speed;
 [SerializeField]
 private Rigidbody2D rb;
 [SerializeField]
 private Animator anim;
 [SerializeField]
 private float jumpForce;
 [SerializeField]
 private SpriteRenderer sr;

 private Vector2 movement;

 // Update is called once per frame
 void Update()
 {
    movement.x = Input.GetAxisRaw("Horizontal");
 }

 void FixedUpdate() {
    Move();
    Jump();
    Attack();
 }

 void Move()
 {
   if (movement.x > 0) {
       sr.flipX = false;
   } else if (movement.x < 0) {
       sr.flipX = true;
   }
   anim.SetBool("running", movement.x != 0);
   rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime); 
}

void Jump()
{
    if (Input.GetKeyDown("space")) {
        Debug.Log("space pressed");
        rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
    }
}

void Attack()
{
    if (Input.GetKeyDown(KeyCode.J)) {
        anim.SetTrigger("attack");
    }
}
}

It is really interesting case because I am able to move and attack, but I can t jump. The condition of jump is correct because "space pressed" is logged. I also tried to add Y velocity, but it also doesn't work. Is someone know this problem solving?

character inspector1 character inspector2


Solution

  • I think I figured it out. This line causes problems:

    rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime); 
    

    The MovePosition function, according to the documentation, moves the position of the object by giving it a velocity that will make it go to the desired location in one frame. This would interfere with the force created from the jump, effectively overriding the force of your jump. You should not use both AddForce and MovePosition in the same frame.