Answer the question
In order to leave comments, you need to log in
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
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;
}
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question