问题描述
GetComponent<Rigidbody2D>().AddForce(transform.forward * Time.deltaTime * forceGathered,ForceMode2D.Impulse);
不会使游戏对象在2D Unity中移动。
我想根据另一个游戏对象的旋转方向施加力量gameobject
。
解决方法
GetComponent()
需要一个参数,在您的情况下为Rigidbody2D
,因此应如下所示:
GetComponent(typeof(Rigidbody2D)).AddForce(transform.forward * Time.deltaTime * forceGathered,ForceMode2D.Impulse);
...而简称为:
GetComponent<Rigidbody2D>().AddForce(transform.forward * Time.deltaTime * forceGathered,ForceMode2D.Impulse);
此外,我建议您缓存Rigidbody2D
组件,因为每次需要访问GetComponent()
时,它的使用都会变得非常昂贵。
最好在开始时将其缓存:
Rigidbody2D rg;
void Start(){
rg = GetComponent<Rigidbody2D>();
}
void YourMovementFunction(){
if (!rg) return;
rg.AddForce(transform.forward * Time.deltaTime * forceGathered,ForceMode2D.Impulse);
}