我正在制作一个 2d 弹球游戏并使用 BoundingSphere 作为命中框,作为捷径。
我遇到的问题是很多东西一直在旋转,我需要找到一种方法来计算当球撞击其他圆形物体时“准确”的回弹角度。
任何帮助,轻推和线索将不胜感激
/Edit 找不到任何东西,但设法解决了这个问题,有点工作
一旦检测到两个 BoundingSphere 之间的碰撞,就会调用此方法。
private void CollisionRebound(Sprites.BaseSprite attacker, Vector2 defender)
{
//Work out the rotation that would result in a "dead on" collision
//thus rebounding the attacker straight back the way they came.
float directHitRotation = (float)Math.Atan2(defender.Y - attacker.Position.Y , defender.X - attacker.Position.X);
//only really needed if the rotation is a negative value but is easier to work from in general.
float attackerRotation = attacker.rotation;
//This makes the rotation a positive number, it cant be less that -2PI
//so adding 2PI will leave us with a positive rotation.
if (attackerRotation < 0)
{
attackerRotation += (float)(Math.PI * 2);
}
//If the rotation is greater than the "dead on" rotation the rotation
//needs to increase.
if (attackerRotation > directHitRotation)
{
//we add "PiOver2" or "90 degrees" to "dead on" rotation because we do, dont know enough
//trig to explain it just know it works, we then add 90 degrees minus the difference between
//our two rotation to give us our outgoing angle, the +0.01f is for the rare case where the
//difference is 90 which would give us no change in rotation but if the two spheres have collided
//(which they have to before coming to this code chunk) there will be at least some change.
attackerRotation = directHitRotation + (float)MathHelper.PiOver2 + ((float)MathHelper.PiOver2 -
(attackerRotation - directHitRotation) + 0.01f);
}
//If the rotation is less than the "dead on" rotation the rotation
//need to decrease.
else if (attackerRotation < directHitRotation)
{
//same as previous chunk but we will be minusing the angle
attackerRotation = directHitRotation - (float)MathHelper.PiOver2 - ((float)MathHelper.PiOver2 -
(attackerRotation - directHitRotation) - 0.01f);
}
else if (attackerRotation == directHitRotation)
{
//either of the two calculations could be used here but would result in the same outcome
//which is rotating the attacker 180 degrees, so just add 2PI instead.
attackerRotation += (float)Math.PI;
}
//Here we just assign out new output rotation to the attacker entity.
attacker.rotation = attackerRotation;
}
只是偶尔让“攻击者”粘在“防守者”身上,有什么解决这个问题的建议吗?
添加注释以向有兴趣使用它的其他人解释代码。