C# 为什么';我的投射物游戏对象不能移动吗?
我已经尝试了许多其他解决方案,但没有一个对我有效。C# 为什么';我的投射物游戏对象不能移动吗?,c#,unity3d,topdown,C#,Unity3d,Topdown,我已经尝试了许多其他解决方案,但没有一个对我有效。 即使我使用了AddForce,我的射弹还是站在那里 这是密码 public Transform gunExitPoint; public int ProjectileVelocity; public GameObject projectilePref; void Update() { if (Input.GetKeyDown(KeyCode.Mouse0)) { GameObject shot = Instan
即使我使用了
AddForce
,我的射弹还是站在那里
这是密码
public Transform gunExitPoint;
public int ProjectileVelocity;
public GameObject projectilePref;
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
GameObject shot = Instantiate(projectilePref, gunExitPoint.position, gunExitPoint.rotation);
Rigidbody2D rb = shot.GetComponent<Rigidbody2D>();
rb.AddForce(transform.forward * ProjectileVelocity * Time.deltaTime, ForceMode2D.Impulse);
}
}
公共转换gunExitPoint;
公共安全;
公共游戏对象projectlepref;
无效更新()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
GameObject shot=实例化(ProjectlePref、gunExitPoint.position、gunExitPoint.rotation);
Rigidbody2D rb=shot.GetComponent();
rb.AddForce(transform.forward*projectlevelocity*Time.deltaTime,ForceMode2D.pulse);
}
}
仅根据这里的内容,假设这是一个完整的示例,那么您的int
变量projectlevelocity
是未赋值的。未分配的整数
类型默认为0
。乘以0
得到一个0
值。如果你使用它作为你的力,那么你的射弹将不会去任何地方。在更改我的代码并使用调试(感谢gmiley)后,我能够将力添加到我的射弹上,然后我将刚体2d更改为动态,并将速度提升到1000f。下面是代码(不幸的是有点草率)
公共矢量2推力;
公共交通点;
公共int Projectlevelocity=1000;
公共游戏对象projectlepref;
//在第一帧更新之前调用Start
void Start()
{
}
无效更新()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
GameObject shot=实例化(ProjectlePref、gunExitPoint.position、gunExitPoint.rotation);
Rigidbody2D rb=shot.GetComponent();
推力=transform.up*投射性;
rb.附加力(推力、力模式2D.脉冲);
}
}
什么是projectlevelocity
设置为?我在编辑器中分配了它,它错了吗?如果调试程序并在rb.AddForce()
调用上设置断点和/或在projectlevelocity
上设置手表,你能看到它不是0
吗?我如何设置断点?
public Vector2 thrust;
public Transform gunExitPoint;
public int ProjectileVelocity = 1000;
public GameObject projectilePref;
// Start is called before the first frame update
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
GameObject shot = Instantiate(projectilePref, gunExitPoint.position, gunExitPoint.rotation);
Rigidbody2D rb = shot.GetComponent<Rigidbody2D>();
thrust = transform.up * ProjectileVelocity ;
rb.AddForce(thrust, ForceMode2D.Impulse);
}
}