Hello,
I am picking up Unity as a hobby. I have been following along with Learning C# by Developing Games with Unity 2019 Fourth Edition by Harrison Ferrone. It has been pretty good, but I am having a problem with my player behavior script.
I am at a point where I have added a jump mechanic and a shoot mechanic to the script controlling my playable character – but for some mystifying reason when I push my shoot button (Mouse 0) my character also jumps. When I push my jump button (spacebar), my character jumps but does NOT shoot. I have done a bit of Googling, but cannot determine why one sets off the other, but not the other way around.
I assume someone with experience could spot my problem in my code, so I will enter that below.
There are numbered comments on the lines that I added my shooting mechanic to.
Thanks for any help you might provide!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBehavior : MonoBehaviour
{
public float moveSpeed = 10f;
public float rotateSpeed = 75f;
public float jumpVelocity = 5f;
public float distanceToGround = 0.1f;
public LayerMask groundLayer;
//1
public GameObject bullet;
public float bulletSpeed = 100f;
private float vInput;
private float hInput;
private Rigidbody _rb;
private CapsuleCollider _col;
void Start()
{
_rb = GetComponent<Rigidbody>();
_col = GetComponent<CapsuleCollider>();
}
void Update()
{
vInput = Input.GetAxis("Vertical") * moveSpeed;
hInput = Input.GetAxis("Horizontal") * rotateSpeed;
if(IsGrounded() && Input.GetKeyDown(KeyCode.Space))
{
_rb.AddForce(Vector3.up * jumpVelocity, ForceMode.Impulse);
}
}
void FixedUpdate()
{
Vector3 rotation = Vector3.up * hInput;
Quaternion angleRot = Quaternion.Euler(rotation * Time.fixedDeltaTime);
_rb.MovePosition(this.transform.position + this.transform.forward * vInput * Time.fixedDeltaTime);
_rb.MoveRotation(_rb.rotation * angleRot);
//2
if (Input.GetMouseButtonDown(0))
{
//3
GameObject newBullet = Instantiate(bullet, this.transform.position, this.transform.rotation) as GameObject;
//4
Rigidbody bulletRB = newBullet.GetComponent<Rigidbody>();
//5
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;
}
}