U
U
Uncle Bogdan2021-08-30 17:42:34
Unity
Uncle Bogdan, 2021-08-30 17:42:34

Why does the behavior of the player's physics change when I add a script to an object?

Tipo added a script to the object, and it began to fall very slowly and does not jump. Removed the component and it started to fall normally.

What's the catch?

The code:

using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class PlayerMovement : MonoBehaviour
{
    [Header("Settings")]
    [SerializeField] private float _walkSpeed;
    [SerializeField] private float _jumpForce;

    [Header("Components")]
    [SerializeField] private Rigidbody2D _rigidbody;

    private void FixedUpdate()
    {
        Walk();
    }

    private void Update()
    {
        if(Input.GetButtonDown("Jump"))
        {
            Jump();
        }
    }

    private void Walk()
    {
        var direction = Input.GetAxisRaw("Horizontal");

        _rigidbody.velocity = Vector2.right * direction * _walkSpeed;
    }

    private void Jump()
    {
        print("Jump");

        _rigidbody.AddForce(Vector2.up * _jumpForce, ForceMode2D.Impulse);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pashara, 2021-08-30
@pashara

Because every frame you overwrite the speed value calculated by the engine:

private void Walk()
{
    var direction = Input.GetAxisRaw("Horizontal");
    _rigidbody.velocity = Vector2.right * direction * _walkSpeed;
}

This code should not work when the object falls.

N
Nikolai Sokolov, 2021-08-30
@NikS42

In the example, there is immediately an example of how it should be. As stated in the Unity documentation:


In most cases, you do not need to change the speed directly, as this may be the cause of unrealistic behavior. Don't set the object's speed every physics step, this will result in an unrealistic physics simulation. A typical example where you can change your speed is when jumping in a first person shooter because you need to change your speed immediately.

As pashara said , it can be useful to mute the Walk when the character is jumping, but not always. For example, platform games often allow you to change the horizontal speed while jumping. To do this, you should also use AddForce so that you can jump on the run. Conditionally, an example when the velocity setter can still be useful is a loss in Mario, when the speed is abruptly reset to zero, and the character flies up on the spot.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question