Hey,
I've implemented jumping and moving in my game, but want to prevent infinite jumping. I've tried to integrate a few systems into my game, but have been unable to do so. Can anyone help?
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));
}
}
}
EDIT: Found a solution. Create an empty, make it child of player, then place it where the feet are. Here's the code I used. You have to give all ground a layer, and put that layer in this script.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
//Variables for general movement.
private float moveSpeed = 5f;
private float jumpHeight = 300f;
private Rigidbody2D rigidBody;
//Variables for grounding system.
public bool isGrounded;
public Transform grounder;
public float radius;
public LayerMask ground;
// Use this for initialization
void Start()
{
rigidBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
//Were keys 'A' or 'D' pushed down?
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
{
//Move the object to it's current position * moveSpeed * time.deltaTime.
transform.Translate(new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f));
}
isGrounded = Physics2D.OverlapCircle(grounder.transform.position, radius, ground);
//Was the key 'W' pushed down?
if (Input.GetKeyDown(KeyCode.W) && isGrounded == true)
{
//Add force to the rigid body, none to the x-axis and jumpHeight to the y-axis.
rigidBody.AddForce(new Vector2(0, jumpHeight));
}
}
//Function which draws gizmos, showing the computer's calculations in the form of a sphere.
void OnDrawGizmos()
{
//Color of gizmos is blue.
Gizmos.color = Color.blue;
//Gizmos is to draw a wire sphere using the grounder.transform's position, and the radius value.
Gizmos.DrawWireSphere(grounder.transform.position, radius);
}
}