Hey,
I’ve created a 2D game with basic movement. The jump function works, but allows for infinite jumping. What’re some simple ways I can use to make sure the player is grounded before allowing them to jump? Do you have any other solutions? I’ve tried to follow a few tutorials, but they didn’t work too well. Thanks.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
private float moveSpeed = 5f;
private float jumpHeight = 300f;
private Rigidbody2D rigidBody;
// Use this for initialization
void Start()
{
rigidBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f)
{
transform.Translate(new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f));
}
if (Input.GetKeyDown(KeyCode.W))
{
rigidBody.AddForce(new Vector2(0, jumpHeight));
}
}
}