728x90
반응형
이번엔 총을 만들었습니다. 에셋 간단하게 구한 뒤, 대강 위치 잡아줍니다.
먼저 무기를 바꾸기 위해 WeaponControll을 만들었습니다.
WeaponControll.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponControll : MonoBehaviour
{
[SerializeField] private List<GameObject> weapons;
private int currentWeaponIndex = 0;
private void Start()
{
for (int i = 0; i < weapons.Count; i++)
{
weapons[i].SetActive(i == 0);
}
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
currentWeaponIndex = (currentWeaponIndex + 1) % weapons.Count;
SwitchWeapon(currentWeaponIndex);
}
}
private void SwitchWeapon(int index)
{
for (int i = 0; i < weapons.Count; i++)
{
weapons[i].SetActive(i == index);
}
}
}
E를 누르면 무기를 바꿀 수 있습니다.


이렇게 세팅 했습니다.
RifleAttack.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RifleAttack : MonoBehaviour
{
public Animator animator;
public GameObject bulletPrefab;
public Transform firePoint;
public float fireForce = 30f;
public float fireRate = 0.2f; //발사 간격 (초 단위)
public float rightFireRate = 5f;
public int bulletCount = 5; // 발사할 총알 개수
public float spreadAngle = 15f; // 산탄총 발사 각도
private float nextFireTime = 0f;
private float nextRightFireTime = 0f;
private void Update()
{
if (Input.GetMouseButtonDown(0) && Time.time >= nextFireTime) // 좌클릭
{
nextFireTime = Time.time + fireRate; // 다음 발사 가능 시간 설정
Shoot();
animator.SetTrigger("Idle");
}
if (Input.GetMouseButtonDown(1) && Time.time >= nextRightFireTime) // 마우스 우클릭
{
nextRightFireTime = Time.time + rightFireRate;
ShootShotgun();
animator.SetTrigger("Idle");
}
}
private void Shoot()
{
FireBullet(firePoint.forward);
animator.SetTrigger("Attack");
}
private void ShootShotgun()
{
for (int i = 0; i < bulletCount; i++)
{
float angle = Random.Range(-spreadAngle, spreadAngle);
Quaternion bulletRotation = Quaternion.Euler(0, angle, 0);
Vector3 shootDirection = bulletRotation * firePoint.forward;
FireBullet(shootDirection);
}
animator.SetTrigger("Attack");
}
private void FireBullet(Vector3 direction)
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody rb = bullet.GetComponent<Rigidbody>();
bullet.transform.forward = direction;
rb.useGravity = false;
rb.AddForce(direction * fireForce, ForceMode.Impulse);
}
private void OnDisable()
{
Quaternion rot = Quaternion.Euler(-15, 0, 0);
transform.localPosition = new Vector3(0.8f, 0, 1.2f);
transform.localRotation = rot;
}
}

이렇게 세팅 했습니다.
Animator는 Rifle의 애니메이터고, Bullet Prefab은 총알, FirePoint는 총알 발사 위치입니다.
Fire Force는 힘입니다.
총 좌클릭은 한 발씩 나가며, 우클릭은 5발 씩 나갑니다.
잠깐 보이기는 하지만 좌클릭 시 한 발, 우클릭 시 다섯발이 나가는 모습입니다.
체력 설명 내일 하려고 합니다.
'Unity' 카테고리의 다른 글
3D 테스트 프로젝트 8 (0) | 2025.03.01 |
---|---|
3D 테스트 프로젝트 7 (0) | 2025.02.28 |
3D 테스트 프로젝트 5 (0) | 2025.02.26 |
3D 테스트 프로젝트 4 (0) | 2025.02.25 |
3D 테스트 프로젝트 3 (0) | 2025.02.24 |