简体   繁体   中英

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:

  • The grenade is NOT Kinematic
  • It doesn't work with both gravity on and off
  • No Positions/Rotations are frozen
  • There is a rigid body attatched
  • There isn't a character controller attached to the grenade
  • The mass is only one

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:

检查员

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM