Hello, I’m relatively new to C# and Unity, and I would like to add the ability to jump using the Input.GetButtonDown
method because I want to give the option to use the keyboard and controller. Here’s the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6f;
public float gravity = -8f;
private CharacterController controller;
void Start ()
{
controller = GetComponent<CharacterController> ();
}
void Update ()
{
float deltaX = Input.GetAxis("Horizontal") * speed;
float deltaZ = Input.GetAxis("Vertical") * speed;
Vector3 movement = new Vector3(deltaX, 0, deltaZ);
movement = Vector3.ClampMagnitude(movement, speed); //limits speed
movement.y = gravity; //applies gravity
movement *= Time.deltaTime; //to make movement independent of FPS
movement = transform.TransformDirection(movement);
controller.Move(movement);
}
}
Thank you very much in advance.
P.S. I will appreciate any pointers you can give me to become a better programmer (books, courses, articles, etc.)
I found the answer on youtube, here’s the link to the video: Jump And Gravity - Game Mechanics - Unity 3D - YouTube
and here is the script, All I did was implement his tutorial into mine:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6f;
public float jumpForce = 10f;
private float gravity = 14f;
private float verticalVelocity;
private CharacterController controller;
void Start ()
{
controller = GetComponent<CharacterController> ();
}
void Update ()
{
float deltaX = Input.GetAxis("Horizontal") * speed;
float deltaZ = Input.GetAxis("Vertical") * speed;
Vector3 movement = new Vector3(deltaX, 0, deltaZ);
movement = Vector3.ClampMagnitude(movement, speed); //limits speed
if (controller.isGrounded)
{
verticalVelocity = -gravity * Time.deltaTime;
if (Input.GetButtonDown("Jump"))
{
verticalVelocity = jumpForce;
}
}
else
{
verticalVelocity -= gravity * Time.deltaTime;
}
movement.y = verticalVelocity; //applies gravity
movement = transform.TransformDirection(movement);
controller.Move(movement * Time.deltaTime);
}
}
I hope this can help people trying to make games where they need their players to jump.