아카이브

총알발사 본문

유니티 심화

총알발사

timbercat 2023. 8. 18. 18:30

BulletController

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BulletController : MonoBehaviour
{
    [SerializeField]
    private float force = 1500f;
    private Rigidbody rBody;
    // Start is called before the first frame update
    void Start()
    {
        this.rBody = this.GetComponent<Rigidbody>();
        //방향 * 힘 
        //월드 좌표 기준으로 힘이 가해짐 
        this.rBody.AddForce(Vector3.forward * this.force);
    }

FireController

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FireController : MonoBehaviour
{
    //총알 프리팹
    public GameObject bullet;
    //총알 발사 좌표
    public Transform firePose;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Fire();
        }
    }

    void Fire()
    {
        //Bullet프리팹을 동적으로 생성(생성객체, 위치, 회전)
        Instantiate(bullet, firePose.position, firePose.rotation);
    }
}

RemoveBullet

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RemoveBullet : MonoBehaviour
{
    private void OnCollisionEnter(Collision collision)
    {
        Debug.Log(collision);

        if (collision.collider.CompareTag("Bullet"))
        {
            Destroy(collision.gameObject); //bullet
        }

        //if (collision.collider.tag == "Bullet")
        //{
        //    Destroy(collision.gameObject); //bullet
        //}
    }
}

결과