So in unity I’m making a 2D platformer and I’m adding jumping. But when the player moves in the air it falls extremely slowly then falls fast again when I stop walking in the air! I have no idea how to fix this problem! I’m not coding gravity I’m using the built in rigidbody gravity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Movement : MonoBehaviour
{
public float speedright = 5;
public Rigidbody2D rb;
public float speedleft = -50;
public Text e;
Scene currentScene;
string sceneName;
public float jumpheight = 300;
public Talking script;
void Start()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
rb.constraints = RigidbodyConstraints2D.FreezeRotation;
bool Seen = false;
Invoke("Starting", 3);
if(Seen == true)
{
script.CanMove = 1;
}
}
private void OnTriggerStay2D(Collider2D collider)
{
if (sceneName == "Bedroom"){
e.text = "E To Interact";
e.gameObject.SetActive(true);
if(Input.GetKeyDown("e"))
{
SceneManager.LoadScene("Hallway");
}
}
}
private void OnTriggerExit2D()
{
e.text = "";
}
void Update()
{
if (script.CanMove == 1)
{
if (Input.GetKey("d"))
{
rb.velocity = new Vector2(speedright, 0 * Time.deltaTime);
rb.transform.eulerAngles = new Vector3(0, 0, 0);
}
if (Input.GetKey("a"))
{
rb.velocity = new Vector2(speedleft, 0 * Time.deltaTime);
rb.transform.eulerAngles = new Vector3(0, 180, 0);
}
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector2.up * jumpheight, ForceMode2D.Impulse);
}
}
}
}
>Solution :
You are setting the y velocity to 0 in each iteration of Update(). Maybe try something like
float currentYVelocity = rb.velocity.y;
if (Input.GetKey("d"))
{
rb.velocity = new Vector2(speedright, currentYVelocity);
rb.transform.eulerAngles = new Vector3(0, 0, 0);
}
if (Input.GetKey("a"))
{
rb.velocity = new Vector2(speedleft, currentYVelocity);
rb.transform.eulerAngles = new Vector3(0, 180, 0);
}
At least, change 0 * Time.deltaTime to some value non zero.
Disclaimer: I have never used Unity, I am just making an observation