2017-02-26 76 views
0

我看到子弹正在随机位置被击发,而实际上并没有在相机的前进方向。这里有什么问题,我应该如何解决? 所以我用池和每个子弹启用此代码的时间运行:为什么我的代码在随机位置触发子弹?

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

回答

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

我总是希望子弹直接射向相机,而不是像这样。我应该如何纠正这一点? –

+0

@CrapshitJetlu就是这样。 – Iggy

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); 
} 
相关问题