首页 > 解决方案 > 我正在制作炮塔,但它不会射击

问题描述

我正在制作一个以设定速率发射子弹的炮塔,但是当计时器完成时,即使它没有说我有任何错误,它也不会产生新的子弹。子弹有一个简单的脚本,它以设定的速度向左或向右移动,并在与物体撞击时被摧毁。炮塔现在没有对撞机,所以我知道这不是问题。

下面是拍摄代码:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class TurretShoot : MonoBehaviour
    {
        public GameObject bullet;
        public int bullet_rate = 10;
        public int timer;
        public Transform SpawnPoint;

        void Start()
        {
            timer = bullet_rate * 10;
        }
    
        // Update is called once per frame
        void Update()
        {
            if (timer == 0)
            {
                Instantiate(bullet, SpawnPoint.transform);
                timer = bullet_rate * 10;
            }
            else
            {
                timer -= 1;
            }
        }
    }

这是项目符号代码:

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

public class BulletMove : MonoBehaviour
{
    public int moveDirection;
    public int moveSpeed;

    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        this.transform.position += new Vector3(moveDirection * moveSpeed, 0, 0);
    }

    void onCollisionEnter2D(Collider2D col)
    {
        if (col.GetComponent<Collider>().name != "turret_top")
        {
            Destroy(this);
        }
    }
}

这是炮塔的检查员:

在此处输入图像描述

标签: c#unity3d

解决方案


可能正在发生的事情是它在生成时被摧毁。

我的炮塔上没有对撞机

你不是在 turrent 实例化它。您只是在实例化父级时设置它:

public static Object Instantiate(Object original, Transform parent);

这意味着它可能正在产卵Vector3.Zero并立即消失。而是使用以下重载方法:

public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);

这样你就可以在你想要的位置生成它。这就是你要做的事情:

var bulletObj = Instantiate(bullet, SpawnPoint.transform.position, Quaternion.Identity);
bulletObj.transform.parent = SpawnPoint.transform;
timer = bullet_rate * 10;

推荐阅读