Question by
Purpleomen · Feb 09, 2021 at 03:24 PM ·
2d-platformerjumpingcharacter controller
Turn off y velocity in 2d Platformer
Hello everyone.
What I want to do is to cut a jump midair by turning off the y velocity midair (like in Hollow Knight). I managed to do that with: rb.velocity = new Vector2(rb.velocity.x, 0f); but my problem is when I cut the jump and I am midair, if I repeat the release jump button process, the whole thing happens again, the character staggers as long as I am releasing the jump button continously. I would like to be able to do that only once when I am off the ground. I am a noob when it comes to coding so I don't really know what to do.
Thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class PlayerController : MonoBehaviour {
public Animator animator;
private Rigidbody2D rb;
public float speed;
private float moveInput;
public float jumpForce;
private bool isGrounded;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private bool facingRight = true;
public float jumpDownForceY = 0;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
if (Input.GetButtonDown("Jump") && rb.velocity.y == 0)
rb.AddForce(Vector2.up * 700f);
if (Mathf.Abs(moveInput) > 0 && rb.velocity.y == 0)
animator.SetBool("Running", true);
else
animator.SetBool("Running", false);
if (rb.velocity.y == 0)
{
animator.SetBool("Jumping", false);
animator.SetBool("Falling", false);
}
if (rb.velocity.y > 0.2)
{
animator.SetBool("Jumping", true);
}
if (rb.velocity.y < 0)
{
animator.SetBool("Jumping", false);
animator.SetBool("Falling", true);
}
if (isGrounded == true && Input.GetButtonDown("Jump"))
{
isJumping = true;
jumpTimeCounter = jumpTime;
rb.velocity = Vector2.up * jumpForce;
}
if (Input.GetButton("Jump") && isJumping == true)
{
if (jumpTimeCounter > 0){
rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
} else {
isJumping = false;
}
}
if (Input.GetButtonUp("Jump"))
{
isJumping = false;
rb.velocity = new Vector2(rb.velocity.x, 0f);
}
}
void FixedUpdate()
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
Flip(moveInput);
}
private void Flip(float moveInput)
{
if (moveInput > 0 && !facingRight || moveInput < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Where is the Jump Input in the default 2d platform controller? 0 Answers
I can't do jump in my 2D game 1 Answer
Varible jump heights 2 Answers
Changing shape of player jump path 0 Answers