为什么我的代码在随机位置发射子弹?

时间:2017-02-26 11:38:37

标签: unity3d unity5

我看到子弹是在随机位置发射的,而不是实际上在相机的前进方向。这里有什么问题,我该如何解决? 所以我正在使用池化,每次启用子弹时都运行此代码:

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);
     }

2 个答案:

答案 0 :(得分:0)

首先确保代码无需池化即可。其次禁用子弹上的对撞机组件(它们可能与自身发生碰撞)。

我已经在我的机器上快速尝试了这个,这是我得到的结果。

enter image description here

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);
    }
}

答案 1 :(得分:0)

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

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);
}