using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private float speed = 5f;
private float mouseX;
private float jumpVelocity = 5f;
public float distanceToGround = 0.1f;
public LayerMask groundLayer;
public GameObject bullet;
private float bulletSpeed = 50f;
private Rigidbody rb;
private CapsuleCollider coll;
void Start()
{
rb = GetComponent<Rigidbody>();
coll = GetComponent<CapsuleCollider>();
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
if (isGrounded() && Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
if (Input.GetMouseButtonDown(0))
{
Fire();
}
}
private void FixedUpdate()
{
MovementLogic();
}
private void LateUpdate()
{
RotateLogic();
}
private void RotateLogic()
{
mouseX = Input.GetAxis("Mouse X");
transform.Rotate(mouseX * Vector3.up);
}
private void MovementLogic()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
transform.Translate(movement * speed * Time.fixedDeltaTime);
}
private bool isGrounded()
{
Vector3 capsuleBottom = new Vector3(coll.bounds.center.x,
coll.bounds.min.y, coll.bounds.center.z);
bool grouned = Physics.CheckCapsule(coll.bounds.center, capsuleBottom,distanceToGround,groundLayer,QueryTriggerInteraction.Ignore);
return grouned;
}
private void Jump()
{
rb.AddForce(Vector3.up * jumpVelocity, ForceMode.Impulse);
print("Jump");
}
private void Fire()
{
GameObject newBullet = Instantiate(bullet,
transform.position + new Vector3(1, 0, 0),
transform.rotation);
Rigidbody bulletRb = newBullet.GetComponent<Rigidbody>();
bulletRb.velocity = transform.forward * bulletSpeed;
}
}
Replace line 76 with:
transform.position + transform.forward,
If the bullet is large then it can overlap the player and push the player away when the physics engine tries to untangle the objects. You can increase the distance the bullet spawns away from the player like so:
transform.position + transform.forward * distance,
You could also place the bullets on a layer that doesn’t interact with the player.