- Home /
Question by
angrycrocodile1 · Jan 27 at 11:39 AM ·
unity 2drigidbody2dupdatefixedupdate
How do I convert this into Fixed Update for physics and Update for inputs?
So I did some testing in my game and this code below works as intended but I keep seeing that you shoudl use FixedUpdate when dealing with rigidbody. But when I make the code a FixedUpdate the inputs sometimes don't register since FixedUpdates update every 4th frame (running at 200 fps). How Can I convert the inputs into a Update and the physics into a FixedUpdate. Thanks for the help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jump;
float moveVelocity;
public Rigidbody2D rb;
public bool isGrounded;
public bool hasJumped;
void Update()
{
//Grounded and hasn't jumped?
if (isGrounded == false && hasJumped == false)
{
//jumping
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Z) || Input.GetKeyDown(KeyCode.W))
{
hasJumped = true;
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jump);
Debug.Log("Jumped 2/2");
}
}
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Z) || Input.GetKeyDown(KeyCode.W))
{
Debug.Log("Jumped 1/2");
}
moveVelocity = 0;
//Left Right Movement
if (isGrounded == true) //Removes air movement
{
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
{
moveVelocity = -speed;
}
if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
{
moveVelocity = speed;
}
GetComponent<Rigidbody2D>().velocity = new Vector2(moveVelocity, GetComponent<Rigidbody2D>().velocity.y);
}
if (isGrounded == false)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, GetComponent<Rigidbody2D>().velocity.y);
}
}
//Says hey you're on the ground or hey you're not on the ground.
void OnCollisionEnter2D(Collision2D col)
{
hasJumped = false;
Debug.Log("OnCollisionEnter2D");
isGrounded = true;
}
void OnCollisionExit2D(Collision2D col)
{
Debug.Log("OnCollisionExit2D");
isGrounded = false;
}
}
Comment