C# Velocity和AddForce()不统一
在我的FPS游戏中,我试图让我的玩家投掷手榴弹。我知道也有类似的问题,但这些帖子都很老了,它们的答案对我一点帮助都没有。当我尝试使用AddForce()方法投掷手榴弹时,手榴弹只在玩家面前产生,就像从未调用AddForce()方法一样。当我将其速度设置为一个值时,也会发生同样的情况。看来手榴弹根本动不了!我已确保:C# Velocity和AddForce()不统一,c#,unity3d,physics,game-physics,unity5,C#,Unity3d,Physics,Game Physics,Unity5,在我的FPS游戏中,我试图让我的玩家投掷手榴弹。我知道也有类似的问题,但这些帖子都很老了,它们的答案对我一点帮助都没有。当我尝试使用AddForce()方法投掷手榴弹时,手榴弹只在玩家面前产生,就像从未调用AddForce()方法一样。当我将其速度设置为一个值时,也会发生同样的情况。看来手榴弹根本动不了!我已确保: 手榴弹不是运动学的 它不能在重力开启和关闭的情况下工作 没有位置/旋转被冻结 有一个刚体附着在一起 手榴弹上没有附加角色控制器 质量只有一个 我的代码如下: using Unit
- 手榴弹不是运动学的
- 它不能在重力开启和关闭的情况下工作
- 没有位置/旋转被冻结
- 有一个刚体附着在一起
- 手榴弹上没有附加角色控制器
- 质量只有一个
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 ();
}
}
}
使用UnityEngine;
使用系统集合;
使用UnityEngine.UI;
公共类脚本:MonoBehavior{
[field]游戏对象手榴弹;
公共int throwForce=30;
矢量3产卵位置;
//用于初始化
无效开始(){
实例化变量();
}
void实例化变量(){
}
void throwGrenade(){
打印(位置);
GameObject Tempglande=(GameObject)实例化(手榴弹、产卵位置、transform.rotation);
矢量3方向=新矢量3(transform.forward.x,transform.forward.y,transform.forward.z);
刚体rb=glundare.GetComponent();
如果(rb!=null){
rb.速度=方向.归一化*10f;
销毁(10枚手榴弹);
}
否则{
Debug.LogError(“立方体上没有刚体!”);
}
}
//每帧调用一次更新
无效更新(){
spawnPosition=transform.forward+transform.position;
打印(位置);
if(Input.GetMouseButtonDown(1)){
throwGrenade();
}
}
}
检查员:
您不应该将手榴弹的刚体组件存储在rb中而不是手榴弹的刚体中吗?我建议使用Tempglande的刚体,然后修改rb.velocity 比如:
rb=tempgreenade.GetComponent();
编辑:通过删除速度场更正了代码行您不应该将Tempglande的刚体组件存储在rb中而不是手榴弹的刚体中吗?我建议使用Tempglande的刚体,然后修改rb.velocity 比如:
rb=tempgreenade.GetComponent();
编辑:通过删除速度场更正了代码行有趣的是,上面的代码行不应该工作,因为它试图将刚体组件的引用指定给速度场(我认为是矢量3)。但只要OP能工作我想…:我认为提问者纠正了这一点,否则会发出错误信息。有趣的是,上面这一行不应该起作用,因为它试图将刚体组件的引用指定给速度场(我认为是矢量)。但只要OP能工作我想…:我认为询问者纠正了这一点,否则它将发出错误消息。
rb = tempGrenade.GetComponent<Rigidbody> ();