在 Unity 2D 自上而下游戏中击退玩家 [英] Knocking back the Player in a Unity 2D TopDown Game
问题描述
当有东西击中玩家时,可能是敌人或尖刺等,我希望他被击退到与敌人相反的方向.
When something hits the Player, maybe an enemy or spikes etc., I want him to get knocked back in the oppisite direction of the enemy.
所以我已经得到了:
public void ChangeHealth(float healthToAdd, Vector2 objectPosition) // Change the players health, objectPosition = enemies position or something else
{
if (healthToAdd < 0) // incoming damage
{
// ... other stuff
Knockback(objectPosition);
}
// ... other stuff
}
void Knockback(Vector2 objectPosition) // Knockback routine
{
Vector2 knockbackPosition = new Vector2( , ); // calculation is missing here! Calculate the new position by the knockback direction
rigid.MovePosition(Vector2.MoveTowards(playerPos, knockbackPosition, 2 * Time.deltaTime)); // the knock back
}
private void Update() // !! TEST !!
{
if (Input.GetKeyDown(KeyCode.E)) // TEST routine
{
ChangeHealth(-7, new Vector2(10,10)); // decrease players health by 7 and knock him back
}
}
缺少什么:
Vector2 knockbackPosition = new Vector2( , );
我正在寻找像这张图所示的计算:
I am looking for a calculation like this picture is showing:
推荐答案
Vector2 knockbackPosition =
transform.position + (transform.position - objectPosition).normalized *a
<小时>
要理解为什么它等于你必须通读.
To understand why is it equal to that you have to read through.
三个点:E、P、K(敌人、玩家、击退)
There are three points: E,P,K (Enemy, Player, Knockback)
还有一个标量:a(这个值越大,你的击退就越多)
And one scalar number: a (the greater this value is, the more knockback you'll have)
现在从你的照片:
PK = EP*a
将向量扩展为两点之间的距离:
expand vectors into distances between two points:
(K-P) = (P-E)*a
计算K的位置:
K = P + (P-E)*a
不过有一个问题.(感谢 Rotem)使用这个公式:
There is one problem though. (thanks to Rotem) with this formula as it is:
你会期待距离更近的对手更大的击退.
you'd expect a bigger knockback from a closer opponent.
我们不希望击退取决于 P 和 E 之间的距离.
We don't want the knockback to be dependent on the distance between P and E.
为了消除对前者的依赖,在乘以 a 之前对向量进行归一化
To remove the dependency on the former, normalize the vector before multiplying by a
所以我们添加 .normalized
以仅使用 (P-E) 的方向而不是它的原始向量
So we add .normalized
to use just the direction of (P-E) instead of its original vector
这篇关于在 Unity 2D 自上而下游戏中击退玩家的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!