- Home /
Question by
ohammond111 · Mar 02, 2020 at 08:49 AM ·
2dmovement2d-platformerplatformer
Can't change direction mid-jump
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);
}
}
}
Comment
Answer by Sxythe · Mar 02, 2020 at 09:01 AM
That's because your movement is in this if statement
if (Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground")))
You should be able to jump mid air if you move it out of the if statement like this
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);
Your answer
![](https://koobas.hobune.stream/wayback/20220612224243im_/https://answers.unity.com/themes/thub/images/avi.jpg)