Okay this topic confuse the hell out of me since weeks. We have now a code:
if (Input.GetButtonDown("Jump"))
{
myRigidbody.AddForce(new Vector2(0.0f, jumpForce), ForceMode2D.Impulse);
}
Okay we have two things here. An Input who belongs in Update and an Addforce, belongs in FixedUpdate… so how do you seperate them? Because according to Unity:
Fixed Update comes first and Update second.
…So you have to apply force first and then check for Inputs? What? ho… I’m really confused right now.
Second we have this example:
float moveInput = Input.GetAxis("Horizontal");
myRigidbody.velocity = new Vector2(moveInput * (speed * Time.deltaTime * 100), myRigidbody.velocity.y);
I can’t put the second line in Fixed Update because moveInput is in another method…
I tried to seperate everything nice and clean an my jump still doesn’t work occasionally.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInput : MonoBehaviour
{
Rigidbody2D myRigidbody;
[SerializeField] float speed = 10;
[SerializeField] float jumpForce = 10;
[SerializeField] float groundCheckRadius = 0.01f;
[SerializeField] Transform groundCheck;
[SerializeField] LayerMask whatIsGround;
bool isGrounded;
bool canJump;
bool jumpInput;
Vector2 movement;
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
}
private void Update()
{
float moveInput = Input.GetAxis("Horizontal");
movement = new Vector2(moveInput, 0.0f);
myRigidbody.velocity = new Vector2(moveInput * (speed * Time.deltaTime * 100), myRigidbody.velocity.y);
if (Input.GetButtonDown("Jump"))
{
jumpInput = true;
}
else
{
jumpInput = false;
}
}
private void FixedUpdate()
{
//myRigidbody.AddForce(movement * speed);
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
if (isGrounded)
{
canJump = true;
}
else
{
canJump = false;
}
if (canJump && jumpInput)
{
myRigidbody.AddForce(new Vector2(0.0f, jumpForce), ForceMode2D.Impulse);
}
Debug.Log(canJump);
}
}