在我的FPS游戏中,我试图让我的玩家投掷手榴弹。我知道有类似的问题,但帖子很旧,答案对我来说根本没有帮助。当我尝试使用AddForce()方法进行手榴弹投掷时,手榴弹只是在玩家面前产生,就像从未调用AddForce()方法一样。当我将其速度设置为一个值时,也发生了同样的情况。看起来手榴弹根本不动!我已经确定:
我的代码如下:
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 ();
}
}
}
检查器:
答案 0 :(得分:0)
你不应该把你的tempGrenade的rigidBody组件存储在rb而不是grenade的rigidBody吗?我建议使用tempGrenade的rigidBody,然后修改rb.velocity。
像:
rb = tempGrenade.GetComponent<Rigidbody> ();
编辑:通过删除速度字段
更正了代码行