What is a simple C# script to make a player move using arrow keys and jump when the space bar is pressed.
I have the following script :
using UnityEngine; using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed;
private Rigidbody rb;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
}
What do I do to make the PLayer Jump?
P.S I am a beginner and I have an upcoming examination in 2 days and I needto know how to do this script. Please reply ASAP
Answer by vittu1994 · May 28, 2016 at 07:19 PM
You will need to create a coroutine for your jump mechanics which is another type of function. You will need to make some constraints on your jumping to work properly:
bool isGrounded = false;
bool canJump = true;
IEnumerator Jump()
{
//your jump code
canJump = false;
yield return new WaitForSeconds(1);
canJump = true;
}
You will need a bool to check when the player is in contact with the ground and it will change when he is at ground or up in the sky. When the player is on the ground he can access this coroutine.
When accessing this code in FixedUpdate():
if(canJump)
{
if(isOnGround && Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(Jump());
}
}
Test this out, it might not be what u want exactly but u can fix and improve the code for your liking in how you want your jumping to act out