简体   繁体   中英

Player Jumping Height is not consistent - Unity

I am working on a 2D Platform game, and i realized that the player's jumping function doesn't work the same way every time, for example. The jumping height is different if the player jumps while moving/running or if the player jumps without moving.

I have 2 separated functions Move() and Jump(), Move() uses transform.Translate to make the player move, and Jump() uses rigidBody.AddForce() to make the player jump. I've already tried to change the player Move() function to use rigidBodies to make the player move instead of using transform.Translate(). And it didn't worked.

I've also tried make the player jump using transform.Translate, which solved the inconsistent jumping height problem, but the player just teleports up instead of jumping

this is a representation of my code structure, not the actual code, because the actual code is like 600 lines

public class Player
{
    float JumpSpeed;
    bool isGrounded;

    void Update()
    {
        if (Input.GetKey(KeyCode.A))
            Move(Directions.Left);

        if (Input.GetKey(KeyCode.D))
            Move(Directions.Right);

        if (Input.GetKeyDown(KeyCode.Space))
            Jump(JumpSpeed);
    }

    public void Move(Directions dir)
    {
        Vector2 speed;
        //figure out speed and etc...

        //makes the player move in the right direction and speed
        transform.Translate(speed * Time.deltaTime);
    }

    public void Jump(float speed)
    {
        if(isGrounded)
            rigidBody.AddForce(new Vector2(0, speed * Time.deltaTime), ForceMode2D.Impulse);
    }
}

Not sure if this is specifically your issue, but using translate to move the player and then adding force to jump isn't really the best way to approach the problem.

I would look into using the velocity part of the rigidbody for both the jump and the movement. This would prevent any weirdness that Translating the object could cause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM