【问题标题】:Why my code fires bullet at random positions?为什么我的代码在随机位置发射子弹?
【发布时间】:2017-03-24 11:09:11
【问题描述】:

我看到子弹是在随机位置发射的,实际上并不是在摄像机的前方。这里有什么问题,我应该如何解决? 所以我正在使用池,每次启用项目符号时都会运行此代码:

private void OnEnable()
     {
         transform.position = Camera.main.transform.position;
         transform.rotation =Quaternion.identity;
         GetComponent<Rigidbody>().AddForce((Camera.main.transform.forward + new Vector3(0, 0, 0)) * 5000);
         Invoke("Destroy", 1.5f);
     }

我也把它改成了下面的代码,但即使是第二个也不起作用。

 private void OnEnable()
     {
         Rigidbody rb = GetComponent<Rigidbody>();
         rb.position = Camera.main.transform.position;
         rb.rotation = Quaternion.identity;
         rb.AddForce((Camera.main.transform.forward + new Vector3(0, 0, 0)) * 5000);
        Invoke("Destroy", 1.5f);
     }

【问题讨论】:

    标签: unity3d unity5


    【解决方案1】:

    首先确保代码在没有池化的情况下工作。其次禁用子弹上的碰撞器组件(它们可能会与自己发生碰撞)。

    我很快在我的机器上尝试了这个,这就是我得到的结果。

    using UnityEngine;
    
    public class BulletController : MonoBehaviour
    {
        [SerializeField]
        GameObject bulletPrefab;
    
        void Update()
        {
            GameObject bullet = Object.Instantiate(bulletPrefab);
            Rigidbody body = bullet.GetComponent<Rigidbody>();
            body.position = Camera.main.transform.position;
            body.AddForce(Camera.main.transform.forward * 75f, ForceMode.Impulse);
        }
    }
    

    【讨论】:

    • 我总是希望子弹在相机的正前方射出,而不是这样。我应该如何纠正这个问题?
    【解决方案2】:

    这是我用于方向、位置和速度变量的代码。

    void Inception::shootGeode(std::string typeGeode, const btVector3& direction) {
    
        logStderr(VERBOSE, "MESSAGE: Shooting geode(s)...\n");
    
        std::shared_ptr<Geode> geode;
    
        glm::vec3 cameraPosition = m_camera->getPosition();
        btVector3 position = glm2bullet(cameraPosition + 3.0f * glm::normalize(m_camera->getTarget() - cameraPosition));
    
        if (typeGeode == "cube")
            geode = m_objectFactory->createCube("cube", new btBoxShape(btVector3(1.0f, 1.0f, 1.0f)), position, "dice");
    
        if (typeGeode == "sphere")
            geode = m_objectFactory->createSphere("sphere", new btBoxShape(btVector3(1.0f, 1.0f, 1.0f)), position);
    
        btVector3 velocity = direction;
        velocity.normalize();
        velocity *= 25.0f;
    
        geode->getRigidBody()->setLinearVelocity(velocity);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-28
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多