gun game
// FPSController.cs
using UnityEngine;
public class FPSController : MonoBehaviour
{
public float walkSpeed = 5f;
public float runSpeed = 10f;
public float jumpForce = 5f;
public float mouseSensitivity = 2f;
private CharacterController controller;
private Vector3 moveDirection;
private float verticalRotation = 0f;
void Start()
{
controller = GetComponent();
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
// Mouse Look
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
verticalRotation -= mouseY;
verticalRotation = Mathf.Clamp(verticalRotation, -90f, 90f);
Camera.main.transform.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
transform.Rotate(0f, mouseX, 0f);
// Movement
float speed = Input.GetKey(KeyCode.LeftShift) ? runSpeed : walkSpeed;
float moveX = Input.GetAxis("Horizontal") * speed;
float moveZ = Input.GetAxis("Vertical") * speed;
moveDirection = transform.right * moveX + transform.forward * moveZ;
// Jump
if(controller.isGrounded && Input.GetButtonDown("Jump"))
{
moveDirection.y = jumpForce;
}
moveDirection.y += Physics.gravity.y * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
// GunScript.cs
using UnityEngine;
public class GunScript : MonoBehaviour
{
public float damage = 25f;
public float range = 100f;
public float fireRate = 0.2f;
public ParticleSystem muzzleFlash;
public GameObject impactEffect;
private float nextFireTime = 0f;
void Update()
{
if(Input.GetButton("Fire1") && Time.time >= nextFireTime)
{
nextFireTime = Time.time + fireRate;
Shoot();
}
}
void Shoot()
{
muzzleFlash.Play();
RaycastHit hit;
if(Physics.Raycast(Camera.main.transform.position,
Camera.main.transform.forward, out hit, range))
{
// Target damage
Enemy enemy = hit.transform.GetComponent();
if(enemy != null)
{
enemy.TakeDamage(damage);
}
// Impact effect
GameObject impact = Instantiate(impactEffect,
hit.point,
Quaternion.LookRotation(hit.normal));
Destroy(impact, 2f);
}
}
}
0 Comments