유니티 심화

SpaceShooter2D - 스페이스바 눌러서 총쏘기

다모아 2023. 8. 17. 01:03

PlayerController

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

public class PlayerController : MonoBehaviour
{
    [SerializeField]
    private float moveSpeed = 3f;

    private Animator anim;
    [SerializeField]
    private BulletController bulletController;
    
    // Start is called before the first frame update
    void Start()
    {
        this.anim = this.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        //움직이고 화면가두기
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");

        Vector2 moveDir = (Vector2.up * v) + (Vector2.right * h);
        this.transform.Translate(moveDir.normalized * this.moveSpeed * Time.deltaTime);

        float clampX = Mathf.Clamp(this.transform.position.x, -2.30f, 2.30f);
        float clampY = Mathf.Clamp(this.transform.position.y, -4.50f, 4.50f);

        this.transform.position = new Vector2(clampX, clampY);

        //왼쪽 방향키 누르면 애니메이션 왼쪽 실행
        if(Input.GetKey(KeyCode.LeftArrow))
        {
            this.anim.SetInteger("State", 1);     
        }
        //오른쪽 방향키 누르면 애니메이션 오른쪽 실행
        else if (Input.GetKey(KeyCode.RightArrow))
        {
            this.anim.SetInteger("State", 2);
        }
        //아무것도 아니라면 애니메이션 센터 실행
        else
        {
            this.anim.SetInteger("State", 0);
        }

        if(Input.GetKeyDown(KeyCode.Space))
        {
            //총알 소환
            bulletController.CreateBullet(this.transform.position);
        }
        //총알이 발사
        bulletController.ShootBullet();
    }
}

 

BulletController

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

public class BulletController : MonoBehaviour
{
    private float bulletSpeed = 4f;

    private GameObject bulletGo;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    //총알 소환
    public void CreateBullet(Vector2 position)
    {
        bulletGo = Instantiate(this.gameObject);
        bulletGo.transform.position = new Vector2(position.x, position.y + 1);
    }

    //총알 발사
    public void ShootBullet()
    {
        if(bulletGo != null)
        {
            bulletGo.transform.Translate(Vector2.up * this.bulletSpeed * Time.deltaTime);
        }
        
    }
}

 

스페이스바를 누르면 기존 총알은 잘 나가는데 다른 총알이 멈춘다..