エッセイマンガ!オタクビアンカップル同棲日記「よめよめ」

同棲中のレズビアンカップルのゆんとあゆむが、日々の生活の様子をマンガや日記にしてお届けするブログです

Unity2Dゲーム制作!敵に弾を当てて倒す簡単な方法!

 

 

EnemyManager

    private float SPEED = 0.01f;    // 移動速度
    private int count = 0;

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

    // Update is called once per frame
    void Update()
    {
        Vector2 position = transform.position;
        count += 1;
        if (count < 500)
        {
            position.x += SPEED;
        }
        else if (count > 500)
        {
            position.x -= SPEED;
        }
        if (count == 1000)
        {
            count = 0;
        }
        transform.position = position;
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.gameObject.CompareTag("Bullet"))
        {
            Debug.Log("BulletCollision");
            Destroy(this.gameObject);
        }
    }

 

 

 

PlayerControl

    private float SPEED = 0.01f;    // 移動速度
    private float JUMP = 2.0f;    // ジャンプの高さ
    private int ground = 0;    // 接地判定
    public int direction = 1; // 方向

    [SerializeField] GameObject gameOverText;
    [SerializeField] GameObject bullet;

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

    // Update is called once per frame
    void Update()
    {
        // キャラクター操作
        Vector2 position = transform.position;

        if (Input.GetKey(KeyCode.RightArrow))
        {            
            position.x += SPEED;
            direction = 1;
            transform.localScale = new Vector2(4, 4);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            position.x -= SPEED;
            direction = -1;
            transform.localScale = new Vector2(-4, 4);
        }
        if (Input.GetKeyDown(KeyCode.LeftControl))
        {
            if (ground == 0)
            {
                Debug.Log("Jump");
                position.y += JUMP;
            }
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Instantiate(bullet, transform.position, transform.rotation);
            Debug.Log("shot");
        }

        transform.position = position;
    }

    // トラップ接触判定
    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.tag == "Trap" || col.tag == "Enemy")
        {
            GameOver(); 
        }
    }

    // 接地判定
    void OnTriggerStay2D(Collider2D col)
    {
        if (col.tag == "Ground")
        {
            ground = 0;
        }
    }
    // ジャンプ判定
    void OnTriggerExit2D(Collider2D col)
    {
        if (col.tag == "Ground")
        {
            ground = 1;
        }
    }

    // GameOver処理
    void GameOver()
    {
        gameOverText.SetActive(true);
        this.gameObject.SetActive(false);
        Debug.Log("GameOver");
    }