Aaron Ge
Aaron Ge

Reputation: 278

Velocity and AddForce() are not working in Unity

In my FPS Game, I am trying to make my player throw a grenade. I know there are similar questions like this, but the posts are old and they the answers did not help me at all. When I tried to make my grenade throw using the AddForce() method, the grenade merely spawned right in front of the player, like the AddForce() method was never called. The same happened when I set its velocity to a value. It seems like the grenade won't move at all! I have made sure that:

My code is below:

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:

Inspector

Upvotes: 1

Views: 1506

Answers (1)

Dayman75
Dayman75

Reputation: 176

Shouldn't you store the tempGrenade's rigidBody Component in rb instead of grenade's rigidBody? I would recommend using tempGrenade's rigidBody and then modifying rb.velocity.

Like:

rb = tempGrenade.GetComponent<Rigidbody> ();

EDIT: Corrected the line of code by removing the velocity field

Upvotes: 0

Related Questions