Rigidbody movement: Changing the Y of transform.position makes my character stutter
I am making a Rigidbody movement script and I want my character to stay on the ground when crouching while he's grounded and pull himself up when crouching while jumping (kind of like in source games). This script works well when standing completely still or jumping without moving in any of the other directions but the moment I move and try to crouch it slows down the movement of the character and stutters. Am I doing something wrong? Any help would be greatly appreciated!
void Crouch()
{
if (playerHeight - crouchHeight > crouchScaleOffset)
{
if (!isCrouching)
{
isCrouching = true;
if (isGrounded && !jumpStart)
crouchedGrounded = true;
else
crouchedGrounded = false;
}
playerHeight = Mathf.Lerp(playerHeight, crouchHeight, Time.deltaTime / crouchDamping);
}
else if (playerHeight != crouchHeight)
{
playerHeight = crouchHeight;
}
ControlPos();
ControlHeight();
}
void StandUp()
{
if (standingHeight - playerHeight > crouchScaleOffset)
{
if (isCrouching)
isCrouching = false;
playerHeight = Mathf.Lerp(playerHeight, standingHeight, Time.deltaTime / crouchDamping);
}
else if (playerHeight != standingHeight)
{
playerHeight = standingHeight;
}
ControlPos();
ControlHeight();
}
//this is what I don't understand
void ControlPos()
{
if (crouchedGrounded)
tf.position += (lastPlayerHeight - playerHeight) / 2 * Vector3.down; //CAUSES STUTTERING
else if (!isGrounded)
tf.position += (lastPlayerHeight - playerHeight) / 2 * Vector3.up; //CAUSES STUTTERING :(
lastPlayerHeight = playerHeight;
}
edit: Nevermind, I found the answer. You should use Rigidbody.MovePosition() to move a rigidbody continuously instead of tf.position https://stackoverflow.com/questions/43714781/proper-way-to-move-rigidbody-gameobject
void ControlPos()
{
if (crouchedGrounded)
rb.MovePosition(rb.position + (lastPlayerHeight - playerHeight) / 2 * Vector3.down);
else if (!isGrounded)
rb.MovePosition(rb.position + (lastPlayerHeight - playerHeight) / 2 * Vector3.up);
lastPlayerHeight = playerHeight;
}
ps. Crouch() en StandUp() are continuously called every frame (with Update()) when needed to crouch and stand up