A
A
Aizharik2018-09-10 20:15:50
C++ / C#
Aizharik, 2018-09-10 20:15:50

The character zigzags or falls when jumping and moving, how to fix it?

The gravity is set low (only -5) and the jump power is also not great. that would be the effect of weightlessness.
Faced such a problem, if you press the jump, and to the left or right, then it is slightly noticeable that the Persian is moving as if going down the stairs, it is noticeable slightly but it hurts the eye.
Also, if you press the jump a second time to the right or left, the Persian may fail. That is, as if all the buttons were pressed, although they were pressed. Or if you go and press the jump, it can work the second time.
As if the presses do not work at the same time or almost at the same time.
The code:

[SerializeField]
    private int lives = 5;

    [SerializeField]
    private float speed = 3f;

    [SerializeField]
    private float jumpForce = 5f;

    private Rigidbody2D rigidbody;
    private Animator animator;
    private SpriteRenderer sprite;
    
    float moveHorizontal;
    float moveVertical;

    private void Awake()
    {
        rigidbody = this.GetComponent<Rigidbody2D>();
        animator = this.GetComponent<Animator>();
        sprite = this.GetComponentInChildren<SpriteRenderer>();
    }

    void FixedUpdate()
    {
        moveHorizontal = Input.GetAxis("Horizontal");
        moveVertical = Input.GetAxis("Vertical");
    }

    void Update()
    {
        if (Input.GetButton("Horizontal")) Run();
        if (Input.GetButtonDown("Vertical")) Fly();

    }


    void Run()
    {
        Vector3 direction = this.transform.right * moveHorizontal;this.transform.position + direction, speed * Time.deltaTime);
        this.transform.Translate(direction * (speed * Time.deltaTime),Space.Self);
    }
    
    private void Fly()
    {
        if (moveVertical > 0) rigidbody.AddForce(this.transform.up * jumpForce, ForceMode2D.Impulse);
        else rigidbody.AddForce(-this.transform.up * (jumpForce + (jumpForce / 5)), ForceMode2D.Impulse);
    }

Rigidbody2D settings:
5b96a68a16d30300386301.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Gaydak, 2018-09-10
@aizhar777

From the obvious
1) Input - not read on FixedUpdate
input only on Update.
2) you have movement in one place by physics (add strength). and right there next you make a move through Translate (essentially teleporting).
3) you have the addition of strength goes to Update. nevertheless, physics must be done in the physics cycle (in FixedUpdate)
in general, or you control the position of the object or control the forces acting on it.
from here all these oddities follow) you confuse "soft" with "hard"))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question