First and foremost I realize this is a huge topic of discussion as I have read various previous posts and looked at Unity documentation and other sites for this answer. The overall response has been to have all inputs within the Update() method and have those inputs made known to the FixedUpdate() method for the actual physics movement. However, I’ve also read that if it is a single input event the input and physics can just be included in the Update() method. With all that said, I am trying to do a simple “jump” on the space bar key down, I have attached my entire script to avoid any confusion.
As I have it, when I test it, the Player game object only jumps every so often, not every single time that I press the space key. I am having the same issue with the second If-statement for the “bullet” firing on left mouse button click. So how can I restructure this to make it work? I am interested in learning how to handle the input (such as key down on space key to jump) in Update() and have the physics (adding the force to handle the jump) occur in FixedUpdate(). ANY HELP/THOUGHTS WOULD BE GREATLY APPRECIATED!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBehavior : MonoBehaviour
{
public LayerMask groundLayer;
private Rigidbody _rb;
private CapsuleCollider _col;
public GameObject bullet;
public float jumpVelocity = 5f;
public float moveSpeed = 10f;
public float rotateSpeed = 75f;
public float distanceToGround = 0.1f;
public float bulletSpeed = 100f;
private float vInput;
private float hInput;
// Start is called before the first frame update
void Start()
{
_rb = GetComponent<Rigidbody>();
_col = GetComponent<CapsuleCollider>();
}
// Update is called once per frame
void Update()
{
vInput = Input.GetAxis("Vertical") * moveSpeed;
hInput = Input.GetAxis("Horizontal") * rotateSpeed;
}
void FixedUpdate()
{
Vector3 rotation = Vector3.up * hInput;
Quaternion angleRot = Quaternion.Euler(rotation * Time.deltaTime);
_rb.MovePosition(this.transform.position + this.transform.forward * vInput * Time.fixedDeltaTime);
_rb.MoveRotation(_rb.rotation * angleRot);
if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
{
_rb.AddForce(Vector3.up * jumpVelocity, ForceMode.Impulse);
}
if (Input.GetMouseButtonDown(0))
{
GameObject newBullet = Instantiate(bullet, this.transform.position + new Vector3(1, 0, 0), this.transform.rotation) as GameObject;
Rigidbody bulletRB = newBullet.GetComponent<Rigidbody>();
bulletRB.velocity = this.transform.forward * bulletSpeed;
}
}
private bool IsGrounded()
{
Vector3 capsuleBottom = new Vector3(_col.bounds.center.x, _col.bounds.min.y, _col.bounds.center.z);
bool grounded = Physics.CheckCapsule(_col.bounds.center, capsuleBottom, distanceToGround, groundLayer, QueryTriggerInteraction.Ignore);
return grounded;
}
}