我正在尝试向游戏中添加脚本,以使每当玩家与敌人碰撞时,他都会受到伤害,但也会被推向相反的方向。我已经尝试实现发布在here
上的Rigidbody2D扩展代码这是我的播放器脚本的一部分:
private void OnCollisionEnter2D(Collision2D other)
{
var magnitude = 5000;
if (other.gameObject.CompareTag("Monster"))
{
TakeDamage(25);
GetComponent<Rigidbody2D>().AddExplosionForce(magnitude, this.transform.position, 500);
}
}
当我在Unity中运行游戏时,只要玩家与敌人发生碰撞,我都会收到此错误消息:
Rigidbody2D.AddForce(force) assign attempt for 'Player' is not valid. Input force is { NaN, NaN }.
UnityEngine.Rigidbody2D:AddForce(Vector2, ForceMode2D)
Rigidbody2DExt:AddExplosionForce(Rigidbody2D, Single, Vector2, Single, Single, ForceMode2D) (at Assets/Scripts/Rigidbody2DExt.cs:20)
Player:OnCollisionEnter2D(Collision2D) (at Assets/Scripts/Player.cs:94)
答案 0 :(得分:1)
欢迎使用StackOverflow。
我建议您尝试:
private void OnCollisionEnter2D(Collision2D other){
Vector2 impulse = new Vector2(-7, 2);
if (other.gameObject.CompareTag("Monster")){
TakeDamage(25);
GetComponent<RigidBody2D>().AddForce(impulse, ForceMode2D.Impulse);
}
}
此外,您还必须找到一种方法来获得所需的方向来推动播放器。例如,如果您从右侧接近敌人,则可能需要将其推向左侧。在我的示例中,您将被向上推动到左侧。让我知道您是否还有问题:)
参考文献here