UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"Create code for a 3d fps shooter game where you fight zombies"
using UnityEngine; using UnityEngine.AI; public class FPSController : MonoBehaviour { public GameObject bulletPrefab; public Transform bulletSpawn; public float bulletSpeed = 30; public float fireRate = 0.5f; private float nextFire = 0.0f; private Camera playerCamera; private CharacterController characterController; private Vector3 moveDirection = Vector3.zero; public float speed = 6.0f; public float gravity = 20.0f; void Start() { characterController = GetComponent<CharacterController>(); playerCamera = Camera.main; } void Update() { MovePlayer(); if (Input.GetButton("Fire1") && Time.time > nextFire) { nextFire = Time.time + fireRate; Shoot(); } } void MovePlayer() { if (characterController.isGrounded) { moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical")); moveDirection = transform.TransformDirection(moveDirection); moveDirection *= speed; } moveDirection.y -= gravity * Time.deltaTime; characterController.Move(moveDirection * Time.deltaTime); } void Shoot() { var bullet = (GameObject)Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation); bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * bulletSpeed; Destroy(bullet, 2.0f); } } public class ZombieAI : MonoBehaviour { public Transform target; private NavMeshAgent agent; void Start() { agent = GetComponent<NavMeshAgent>(); target = GameObject.FindGameObjectWithTag("Player").transform; } void Update() { agent.SetDestination(target.position); } } public class BulletCollision : MonoBehaviour { public int damage = 10; void OnCollisionEnter(Collision collision) { var hit = collision.gameObject; var health = hit.GetComponent<ZombieHealth>(); if (health != null) { health.TakeDamage(damage); } Destroy(gameObject); } } public class ZombieHealth : MonoBehaviour { public int startingHealth = 100; public int currentHealth; void Start() { currentHealth = startingHealth; } public void TakeDamage(int amount) { currentHealth -= amount; if (currentHealth <= 0) { Die(); } } void Die() { Destroy(gameObject); } }