So, I’m new to unity and my first project is a 2d platform. I got the jumping and movement code working but I can’t change direction in the middle of my jump. I saw this other question This One, but their problem was that their movement code was under an if statement meaning it could only jump when grounded but I don’t see anything like that in my code and I can’t change direction while jumping. Any idea what the problem is? My code is here:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Control : MonoBehaviour
{
public Transform groundCheck;
bool grounded = false;
public GameObject player;
public Rigidbody2D rb;
public float speed;
float moveVelocity;
void Update() {
//Jumping
if (rb.velocity.y > 0)
{
grounded = false;
}
if (Input.GetKeyDown((KeyCode.Space)) && (grounded == true))
{
//Jump();
rb.AddForce(new Vector2(0, 1000));
grounded = false;
}
if (Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"))) {
grounded = true;
//horizontal movement
moveVelocity = 0;
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
moveVelocity = -speed; //move left
}
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
moveVelocity = speed; //move right
}
rb.velocity = new Vector2(moveVelocity,rb.velocity.y);
}
}
}