AddForce transform.forward无法在2D整体中使用

问题描述

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);
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...