2016-04-16 127 views
1

在我的FPS遊戲中,我試圖讓我的玩家投擲手榴彈。我知道有類似的問題,但這些帖子是舊的,他們的答案根本沒有幫助我。當我嘗試使用AddForce()方法使我的手榴彈擲出時,手榴彈僅在玩家面前產生,就像從未調用AddForce()方法一樣。當我將其速度設置爲某個值時,也發生了同樣的情況。看起來手榴彈根本不會動!我已經確定的是:Velocity和AddForce()在Unity中不起作用

  • 手榴彈是不是運動
  • 它不與兩個重力和關閉
  • 否/旋轉被凍結
  • 有一個剛體位置attatched
  • 工作
  • 沒有附接到手榴彈字符控制器
  • 的質量是唯一的一個

我的代碼如下:

using UnityEngine; 
using System.Collections; 
using UnityEngine.UI; 



public class Script : MonoBehaviour { 
    [SerializeField] GameObject grenade; 
    public int throwForce = 30; 
    Vector3 spawnPosition; 

// Use this for initialization 
void Start() { 
     instantiateVariables(); 
} 
    void instantiateVariables(){ 



    } 
    void throwGrenade(){ 

     print (spawnPosition); 
     GameObject tempGrenade = (GameObject) Instantiate (grenade, spawnPosition, transform.rotation); 
    Vector3 direction = new Vector3(transform.forward.x, transform.forward.y, transform.forward.z); 

     Rigidbody rb = grenade.GetComponent<Rigidbody>();   
    if (rb != null){ 
    rb.velocity = direction.normalized * 10f; 
     Destroy (tempGrenade, 10); 
    } 
    else { 
     Debug.LogError ("There is no rigid body on your cube!"); 
    } 

    } 
// Update is called once per frame 
void Update() { 


    spawnPosition = transform.forward + transform.position; 
    print (spawnPosition); 
     if (Input.GetMouseButtonDown (1)) { 
      throwGrenade(); 
     } 

} 


} 

督察:

Inspector

回答

0

你不應該存儲tempGrenade的剛體組件在RB,而不是手榴彈的剛體?我會建議使用tempGrenade的rigidBody,然後修改rb.velocity。

像:

rb = tempGrenade.GetComponent<Rigidbody>(); 

編輯:通過刪除速度場

+0

讓我知道,如果它不工作:) – Dayman75

+0

哇更正的代碼行。這就是我所錯過的。謝謝! –

+0

不客氣:) – Dayman75