I was following a tutorial about the basics of making games in Unity. Link to person :https://www.tiktok.com/@individualkex. I came across an issue, when I put the code for jumping in, and I ran the program, then tried to jump, (as you could guess) it did not work. This problem is probably very obvious, so sorry for my inexperience, here is the code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public GameObject groundCheck;
public float moveSpeed = 9.2f;
public float acceleration = 50f;
public float jumpSpeed = 10f;
Rigidbody rigidBody;
float moveX;
int moveDir;
bool grounded;
void Awake() {
rigidBody = GetComponent<Rigidbody>();
}
void Update() {
moveDir = (int)Input.GetAxisRaw("Horizontal");
if(moveDir != 0)
moveX = Mathf.MoveTowards(moveX, moveDir * moveSpeed, Time.deltaTime * acceleration);
else
moveX = Mathf.MoveTowards(moveX, moveDir * moveSpeed, Time.deltaTime * acceleration * 2f);
grounded = Physics.CheckSphere(groundCheck.transform.position, .2f, LayerMask.GetMask("Ground"));
if(Input.GetButtonDown("Jump") && grounded)
Jump();
}
void Jump() {
rigidBody.velocity = new Vector3(rigidBody.velocity.x, jumpSpeed, 0);
}
void FixedUpdate() {
if (rigidBody.velocity.y < .75f * jumpSpeed || !Input.GetButton("Jump"))
rigidBody.velocity = Vector3.up * Physics.gravity.y * Time.fixedDeltaTime * 5f;
rigidBody.velocity = new Vector3(moveX, rigidBody.velocity.y, 0);
}
}
I don't know if this could be a problem with Unity itself, or something related to that, but I just need to get unstuck. Cheers.
CodePudding user response:
The only code that would restrict you from jumping is this:
if(Input.GetButtonDown("Jump") && grounded)
Jump();
Your Jump(); seems to be fine and grounded seems to be fine as well. It seems like it may be a unity editor issue. Make sure you have set your ground to a "Ground" layer. If there is no "Ground" you can't jump.
CodePudding user response:
Oh my god guys, I'm so stupid. I thought, (for SOME reason) that in order to jump, I had to press the top arrow key. I actually had to press the space bar.