- Home /
Player movement and jumping issue
So I am having an issue with my code here. If I click the space bar it will jump which is what I want, but if I click the space bar again while I am in the air it will continue to jump even though it shouldn't. How can I fix this? Secondly I have another section of code (I'll post it in replies) which makes my player move forward automatically, the issue I am having is that when I move left or right it'll slow down the player and it also slows down when I jump, I don't understand how to fix this and too limit how far the player can move left and right. Assistance would be great, thanks
using System.Collections.Generic;
using UnityEngine;
public class player_controls : MonoBehaviour {
public Rigidbody rb;
public float jumpHeight; public float moveSpeed = 10f;
// Use this for initialization void Start () {
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Space)){
GetComponent<Rigidbody>().velocity = new Vector2(GetComponent<Rigidbody>().velocity.x,jumpHeight);
}
if(Input.GetKey(KeyCode.LeftArrow)){
GetComponent<Rigidbody>().velocity = new Vector2(moveSpeed,GetComponent<Rigidbody>().velocity.y);
}
if(Input.GetKey(KeyCode.RightArrow)){
GetComponent<Rigidbody>().velocity = new Vector2(-moveSpeed,GetComponent<Rigidbody>().velocity.y);
}
}
}
Answer by CobbledGames · Jan 06, 2021 at 01:50 PM
One way to deal with the first problem is to check if you've landed with an if statement checking a bool variable. Use OnCollisionEnter to check if your object has landed on the floor and have your bool to check if you are in the air set to true in the OnCollisionEnter method and set the bool to false when you jump.
I'd recomend looking up OnCollisionEnter. It's useful.
Answer by stormz2002 · Jan 06, 2021 at 01:11 PM
Here's the code that allows my player to move forward automatically
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
public Rigidbody rb;
public float ForwardForce = 2000f;
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
rb.AddForce(0, 0, -ForwardForce * Time.deltaTime);
}
}