- Home /
Velocity not updating object position
In a plat-former game I am making I have a player controller that how a jump method in it. The velocity does get changed, I can see it in the info tab on the Rigidbody2D, but the position does not move with it. My Rigid-body is set to dynamic, the mass is 1, there is no drag of any kind, and it's positions are not constrained, as rb.MovePosition works. Here is my player controller code.
public GameObject player;
private Rigidbody2D _rb;
public float speed;
public float jumpForce;
public float fallMultiplier = 2.5f;
public float lowJumpMultiplier = 2f;
private bool _isJumping = false;
private bool _grounded = false;
private Vector2 _movement;
private void Start()
{
_rb = player.GetComponent<Rigidbody2D>();
}
void Update()
{
GetInputs();
}
private void FixedUpdate()
{
Move();
Jump();
}
void GetInputs()
{
_movement.x = Input.GetAxis("Horizontal");
if (Input.GetButtonDown("Jump") && _grounded)
{
_isJumping = true;
_grounded = false;
print("Jump");
}
}
void Move()
{
_rb.MovePosition(_rb.position + _movement * speed * Time.deltaTime);
}
void Jump()
{
if (_isJumping)
{
_rb.velocity = Vector2.up * jumpForce;
}
if (_rb.velocity.y < 0)
{
_rb.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
}
else if (_rb.velocity.y > 0 && !Input.GetButton("Jump"))
{
_rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
_grounded = true;
_isJumping = false;
}
Answer by davidcox70 · Jul 22, 2020 at 05:52 AM
I think don't use velocity to make your jump. Use AddForce instead. The docs generally recommend that we don't write to velocity.
Different subject: You are using time.deltaTime in a fixed update routine. Rather use time.fixedDeltaTime. This is because deltaTime gives you the duration of an update() frame and fixedDeltaTime gives you the duration of a physics update frame. They are not necessarily at the same frequency.
DC
...actually if you must use velocity, just test commenting out your move() routine from FixedUpdate(). It could be that specifying an RB movePosition AND explicit velocity change overwrite each other. $$anonymous$$aybe.
You were right the $$anonymous$$ovePositon was conflicting with the velocity
Your answer
Follow this Question
Related Questions
Horizontal/Parabolic Projectil Movement and Jump for 2D //HELP! 0 Answers
,Rotate a gameobject around another while being attracted by its gravity 1 Answer
2D rigidbody velocity relative to rotation? 0 Answers
how to jump at fixed height but faster 0 Answers
how to make an 2d object move the direction its facing using rigidbody2d.velcoity 1 Answer