- Home /
Rigidbody2D giving incorrect value
Hello. I'm relatively inexperienced coding in C# and I'm trying to make a side scroller platformer on Unity but when I try to read out the y velocity of my Rigidbody2D using a velocity.y it keeps giving me an incorrect value. I'm trying to read out the velocity so I can play three separate animations for the player's jump: One for rising, one for cresting, and one for falling. Rising and cresting work fine, but the value for my player's rigidbody velocity when they start falling stops at around 0.0507 and never drops below 0. When I read the velocity value for the rigidbody in the inspector, it looks normal and drops well below 0 as the player falls, but my debug log only shows 0.0507. Is this a bug? I've posted the script for my player movement below where I've tried to figure this out. Please help if you can and thank you!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController2D controller;
public Animator animator;
float verticalMove = 0f;
public float runSpeed = 60f;
public Rigidbody2D playerRigidbody2D;
float horizontalMove = 0f;
public float attackTime = 0.3f;
private IEnumerator groundAttack;
bool jump = false;
private void Awake()
{
animator.SetFloat("lastDirection", 1);
}
// Update is called once per frame
void Update()
{
animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
verticalMove = Input.GetAxisRaw("Vertical") * controller.JumpSpeed;
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
if (Input.GetButtonDown("Jump"))
{
jump = true;
}
}
void FixedUpdate() {
controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump);
jump = false;
if (controller.m_Grounded == true)
{
if (Input.GetKeyDown("f") && (animator.GetFloat("GroundAttack") == 0))
{
StartCoroutine(groundAttack());
}
}
if (controller.m_Grounded == false && playerRigidbody2D.velocity.y > 0.5f)
{
animator.SetBool("JumpRising", true);
animator.SetBool("JumpCresting", false);
animator.SetBool("JumpFalling", false);
Debug.Log(playerRigidbody2D.velocity.y);
}
else if (controller.m_Grounded == false && playerRigidbody2D.velocity.y < 0.4 && playerRigidbody2D.velocity.y > 0.01)
{
animator.SetBool("JumpCresting", true);
animator.SetBool("JumpRising", false);
animator.SetBool("JumpFalling", false);
Debug.Log(playerRigidbody2D.velocity.y);
}
else if (controller.m_Grounded = false && playerRigidbody2D.velocity.y < 0.01)
{
animator.SetBool("JumpFalling", true);
animator.SetBool("JumpCresting", false);
animator.SetBool("JumpRising", false);
Debug.Log(playerRigidbody2D.velocity.y);
}
I checked and I was actually missing the second =. That seemed to have fixed it! Thanks for the help.
Answer by xxmariofer · Jul 30, 2019 at 10:14 PM
are you missing a == in the last else if or was just a typo coping the script?