Making a fly mechanic while using the same button for jump
I'm trying to make a system where one single button does two different things depending on how it was pressed.
If the player just tap the button they will jump, however if the player holds it they will fly. I want to know if it is possible to do something like that so that they will not conflict with each other.
In my current state it is very inconsistent, sometimes it works well, other times not so much.
Here the script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mainPlayer : MonoBehaviour
{
/*
* Todo:
* Player input/ flytime/ movement/ collision
*
* Fly
* 1-quando prescinar o botao gera uma força que faz o player voar
* 2-quando o tempo de voô for igual a o tempo maximo permetido o player caia
* 3-quando relar no chão o voô reseta
*/
[SerializeField]
internal float speed, flyT, flyMax, flyF, jumpF;
[SerializeField]
internal int score;
Rigidbody2D rg;
BoxCollider2D bx;
private float h;
private bool isFly, isJump;
private void Awake()
{
rg = GetComponent<Rigidbody2D>();
bx = GetComponent<BoxCollider2D>();
}
private void Update()
{
h = Input.GetAxis("Horizontal");
isFly = Input.GetKey("space");
isJump = Input.GetKeyDown("space");
}
private void FixedUpdate()
{
Move();
Fly();
Jump();
}
//função de mover
void Move()
{
Vector2 pos = transform.position;
pos.x += h * speed * Time.deltaTime;
transform.position = pos;
}
//Função de voar
void Fly()
{
if(isFly && flyT < flyMax)
{
rg.AddForce(Vector2.up * flyF);
flyT += Time.deltaTime;
Debug.Log("up");
}
}
void Jump()
{
if(isJump)
{
rg.AddForce(Vector2.up * jumpF, ForceMode2D.Impulse);
Debug.Log("jump");
}
}
void OnCollisionExit2D(Collision2D collision)
{
flyT = 0;
}
}
Comment