How To Make my Player Glide in 2d platformer
Hey I'm new to unity and really wanna make my player glide after he jumps something like
if (Input.GetKeyDown(KeyCode.O) && !grounded) {//Glide }
The code that I'm using for my Player Controller is this
using UnityEngine; using System.Collections;
public class PlayerController : MonoBehaviour {
public float moveSpeed;
public float jumpHeight;
public bool grounded;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Jump if (Input.GetKeyDown(KeyCode.P) && grounded) {
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x,jumpHeight);
}
//Glide
if (Input.GetKeyDown(KeyCode.O) && !grounded)
{
}
//Movement
if (Input.GetKey(KeyCode.A))//right
{
GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
if (Input.GetKey(KeyCode.D))//left
{
GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
}
}
Answer by ggpereira · Oct 08, 2020 at 01:15 AM
For all of you looking for a nice way, check the code below
using UnityEngine;
public class Glider : MonoBehaviour
{
/// <summary>
/// The speed when falling
/// </summary>
[SerializeField]
private float m_FallSpeed = 0f;
/// <summary>
///
/// </summary>
private Rigidbody2D m_Rigidbody2D = null;
// Awake is called before Start function
void Awake()
{
m_Rigidbody2D = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (IsGliding && m_Rigidbody2D.velocity.y < 0f && Mathf.Abs(m_Rigidbody2D.velocity.y) > m_FallSpeed)
m_Rigidbody2D.velocity = new Vector2(m_Rigidbody2D.velocity.x, Mathf.Sign(m_Rigidbody2D.velocity.y) * m_FallSpeed);
}
public void StartGliding()
{
IsGliding = true;
}
public void StopGliding()
{
IsGliding = false;
}
/// <summary>
/// Flag to check if gliding
/// </summary>
public bool IsGliding { get; set; } = false;
}
Then trigger the StartGliding method when you hold the jump button or whatever
Answer by petisnnake · Aug 12, 2016 at 02:41 PM
First of all always multiply your velocity by Time.deltaTime. You need to do that so movement speed is consistent regardless of framerate. (Update is called at different frequency depending on device capabilities)
Second, what do you mean by glide?
Answer by LennyC · Aug 12, 2016 at 04:22 PM
Glide as to the player floats down slowly as if for example. Gravity for the player is 5 but when you hit the glide button and is not grounded gravity is 2.
I Actually found away to do it with this code in my Player Controller
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.O)) {
GetComponent<Rigidbody2D>().gravityScale = 1;
}
if (Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.O))
{
GetComponent<Rigidbody2D>().gravityScale = 5;
}