2017-02-26 77 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); 
} 
相關問題