0
votes

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);
    }
}
1
I'm not seeing anything here that would produce the results you're describing. If you replace your Player code with what's written here, does it still show the same jump height differences? - Ruzihm
I'm not sure you need to multiply the force by Time.deltaTime when using Rigidbody.AddForce. Impulse mode is a momentum and not an acceleration, so the unit is already m/s and not m/s^2. I got the info from this Unity Answers answer - Eliasar
@Eliasar oh excellent point. That could be the cause since running may coincide with a changing framerate. - Ruzihm
even by replacing the actual code with the one written here and stop multiplying the force by Time.deltaTime, it still show difference in the jumping height - Nícolas
@Nicolas Actually, I'm curious, what happens if you use transform.Translate(speed*Time.deltaTime, Space.World);? If the problem is related to the transform being rotated, it may address it. - Ruzihm

1 Answers

1
votes

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.