为精灵添加力量
Adding force to a sprite
我有一个二维角色,我想让它的头掉下来。
加力似乎最合乎逻辑,但我无法获得任何力,而且它还必须取决于角色旋转。因此,如果他侧身躺下,头部必须向左(或右)倾斜。
public GameObject RagdollBody;
HingeJoint2D joint;
bool cut = false;
Rigidbody2D rb;
void Start()
{
joint = GetComponent<HingeJoint2D>();
rb = GetComponent<Rigidbody2D>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Blade" && !cut)
{
joint.enabled = false;
cut = true;
rb.AddForce(-RagdollBody.transform.forward * 500);
}
}
我看了一个使用了-transform 的视频,所以它会朝相反的方向拍摄,这正是我想要的。由于头部总是 0,0,0 旋转,我需要从父级获取它,但它仍然没有添加任何力。
您正在使用 transform.forward
,代表 Z 轴,或者 "inwards",如果您愿意的话,在 2d 游戏中。
如果你想向上增加力(相对于它的方向),我建议改为尝试这个
rb.AddForce(RagdollBody.transform.up * 500);
您可能需要在最后一行使用 "AddRelativeForce" 而不是 "AddForce" 吗?
如果这个脚本放在你启动的头部,你可以试试:
public GameObject RagdollBody;
HingeJoint2D joint;
bool cut = false;
Rigidbody2D rb;
void Start()
{
joint = GetComponent<HingeJoint2D>();
rb = GetComponent<Rigidbody2D>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Blade" && !cut)
{
joint.enabled = false;
cut = true;
rb.AddRelativeForce(Vector2.up * 500);
}
}
或者你可以在一行中得到所有的二维刚体(只是为了节省行数):
public GameObject RagdollBody;
HingeJoint2D joint;
bool cut = false;
void Start()
{
joint = GetComponent<HingeJoint2D>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Blade" && !cut)
{
joint.enabled = false;
cut = true;
GetComponent<Rigidbody2D> ().AddRelativeForce(Vector2.up * 500);
}
}
我有一个二维角色,我想让它的头掉下来。
加力似乎最合乎逻辑,但我无法获得任何力,而且它还必须取决于角色旋转。因此,如果他侧身躺下,头部必须向左(或右)倾斜。
public GameObject RagdollBody;
HingeJoint2D joint;
bool cut = false;
Rigidbody2D rb;
void Start()
{
joint = GetComponent<HingeJoint2D>();
rb = GetComponent<Rigidbody2D>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Blade" && !cut)
{
joint.enabled = false;
cut = true;
rb.AddForce(-RagdollBody.transform.forward * 500);
}
}
我看了一个使用了-transform 的视频,所以它会朝相反的方向拍摄,这正是我想要的。由于头部总是 0,0,0 旋转,我需要从父级获取它,但它仍然没有添加任何力。
您正在使用 transform.forward
,代表 Z 轴,或者 "inwards",如果您愿意的话,在 2d 游戏中。
如果你想向上增加力(相对于它的方向),我建议改为尝试这个
rb.AddForce(RagdollBody.transform.up * 500);
您可能需要在最后一行使用 "AddRelativeForce" 而不是 "AddForce" 吗?
如果这个脚本放在你启动的头部,你可以试试:
public GameObject RagdollBody;
HingeJoint2D joint;
bool cut = false;
Rigidbody2D rb;
void Start()
{
joint = GetComponent<HingeJoint2D>();
rb = GetComponent<Rigidbody2D>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Blade" && !cut)
{
joint.enabled = false;
cut = true;
rb.AddRelativeForce(Vector2.up * 500);
}
}
或者你可以在一行中得到所有的二维刚体(只是为了节省行数):
public GameObject RagdollBody;
HingeJoint2D joint;
bool cut = false;
void Start()
{
joint = GetComponent<HingeJoint2D>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Blade" && !cut)
{
joint.enabled = false;
cut = true;
GetComponent<Rigidbody2D> ().AddRelativeForce(Vector2.up * 500);
}
}