Home > Software engineering >  Cannot seem to make my player jump in unity
Cannot seem to make my player jump in unity

Time:06-21

I'm working on a 2D game in Unity attempting to make my player jump. Despite watching tons of videos and adjusting the code many times, he simply won't jump when I press the space bar. After even checking the input manager in Unity, I'm sure it's a simple fix I'm missing somewhere but I don't see where it could be.

public class FoxyController : MonoBehaviour
{
    Rigidbody2D rigidbody2d; 
    float horizontal;
    float vertical; 
    public float jumpVelocity = 10f; 

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


void Update()
{
    horizontal = Input.GetAxis("Horizontal");
    vertical = Input.GetAxis("Vertical");


    if (Input.GetKey(KeyCode.Space))
    { 
        Jump(); 
    }
}


void FixedUpdate()
{
    Vector2 position= rigidbody2d.position;
    position.x = position.x   4f * horizontal * Time.deltaTime;
    position.y = position.y   4f * vertical * Time.deltaTime; 

    rigidbody2d.MovePosition(position);         
}

void Jump()
{
    rigidbody2d.velocity = Vector2.up * jumpVelocity; 
}

}

CodePudding user response:

Use -> rb.AddForce(Vector2.up * jumpAmount, ForceMode2D.Impulse); where jumpAmount can be multiplayer, you can use 10f as jumpAmount value

CodePudding user response:

Seems like you're confused, because you're trying to use 2 different way. If you want a quick fix Just delete the whole FixedUpdate.

The main problem is when no input occurs, you're setting your position to the same position via horizontal and vertical . You can use Velocity, AddForce or any other way but your math calculation is wrong at here. Always debug your values, if you would check your old and new position after movement, you'd notice that it was the same.

The another mistake you made is using deltaTime instead of the fixed one for physics.

  • Related