UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"Create a script for a 3d fps shooter game where you fight zombies"
using UnityEngine; public class FPSController : MonoBehaviour { public float moveSpeed = 5f; public float jumpForce = 5f; public float gravity = -9.81f; public Transform groundCheck; public float groundDistance = 0.4f; public LayerMask groundMask; public GameObject gun; public GameObject bulletPrefab; public Transform bulletSpawn; public float bulletSpeed = 30f; public float fireRate = 0.5f; private CharacterController controller; private Vector3 velocity; private bool isGrounded; private bool canShoot = true; private void Start() { controller = GetComponent<CharacterController>(); } private void Update() { // Check if player is on the ground isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); if (isGrounded && velocity.y < 0) { velocity.y = -2f; } // Get player input for movement float x = Input.GetAxis("Horizontal"); float z = Input.GetAxis("Vertical"); Vector3 move = transform.right * x + transform.forward * z; controller.Move(move * moveSpeed * Time.deltaTime); // Jump if player presses space and is on the ground if (Input.GetButtonDown("Jump") && isGrounded) { velocity.y = Mathf.Sqrt(jumpForce * -2f * gravity); } // Apply gravity velocity.y += gravity * Time.deltaTime; controller.Move(velocity * Time.deltaTime); // Shoot if player presses left mouse button if (Input.GetButtonDown("Fire1") && canShoot) { Shoot(); } } private void Shoot() { // Spawn bullet and set its velocity GameObject bullet = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation); Rigidbody rb = bullet.GetComponent<Rigidbody>(); rb.velocity = bulletSpawn.forward * bulletSpeed; // Disable shooting for a short time to prevent rapid fire canShoot = false; Invoke("EnableShooting", fireRate); } private void EnableShooting() { canShoot = true; } }