目前我正在以经典的2D几何图形弹跳一个墙球。
墙壁可以在垂直和水平两侧被击中,反射的结果取决于球击中的哪一侧。
我尝试了一些不同的解决方案,但它们让我更加困惑。
如何判断球是否撞击墙壁的垂直或水平方向?
PseudoCode概述:
iterate through each wall
if (collision between ball and wall)
determine if vertical/horizontal hit
calculate new velocity for ball
我使用此代码进行碰撞检测,它就像一个魅力: 来源:Circle-Rectangle collision detection (intersection)
var isCollision = function (_projectile) {
if(direction != undefined){
var circleDistance = {};
circleDistance.x = Math.abs(_projectile.getCenter().x - centerX);
circleDistance.y = Math.abs(_projectile.getCenter().y - centerY);
if (circleDistance.x > (width/2 + _projectile.getRadius())) { return false; }
if (circleDistance.y > (height/2 + _projectile.getRadius())) { return false; }
if (circleDistance.x <= (width/2)) { return true; }
if (circleDistance.y <= (height/2)) { return true; }
var cornerDistance_sq = square(circleDistance.x - width/2) + square(circleDistance.y - height/2);
return (cornerDistance_sq <= (square(_projectile.getRadius())));
}
return false;
};
var square = function(_value){
return _value * _value;
};
谢谢!
答案 0 :(得分:3)
update after question update
Asuming the ball has a direction/velocity vector public void MinimizeApp(string parameter)
{
if (parameter == "-minimized")
{
this.WindowState = FormWindowState.Minimized;
notifyIcon1.Visible = true;
notifyIcon1.BalloonTipText = "Program is started and running in the background...";
notifyIcon1.ShowBalloonTip(500);
Hide();
}
}
and has a radius of dx,dy
(r
, ball.x
are the ball positions of the ball center) do sth like this (have used similar in a billiard game, it is basic geometry and physics):
ball.y
do similar for opposite walls if needed, since velocity vector changes, the new ball position after bouncing (or anyway) will be if (ball.x+ball.dx+r > wallV.x) ball.dx = -ball.dx // ball bounces off the
vertical wall
if ( ball.y+ball.dy+r > wallH.y ) ball.dy = -ball.dy // ball bounces off horizontal wall
Bonus if you add some friction factor (meaning the magnitudes of ball.x += ball.dx; ball.y += ball.dy;
dx
eventually fade away to zero, the ball eventually stops after following a path)
答案 1 :(得分:2)
要正确解决碰撞问题,您无法在X =&gt;上进行测试如果碰撞解决并返回那么y =&gt;的测试如果碰撞解决了y。
你必须首先检查哪个 ax(x OR y)碰撞,当球同时撞到两面墙时也是如此。
所以你不能只用空间来推理:你必须处理时间,并根据球的速度计算所有墙壁的ETA估计时间到达(假设墙壁仍然是)。
伪代码:
minETA = a too big number;
colliderList = [];
for (each wall in walls) {
thisWallETA = computeETA(ball, wall);
if (thisWallETA > minETA) continue;
if (thisWallETA < minETA) {
minETA = thisWallETA;
colliderList.length = 0;
colliderList.push(wall);
continue;
}
if (thisWallETA == minETA) {
colliderList.push(wall);
continue;
}
}
然后当colliderList只有一个项目=&gt;解决相应的问题。如果它有两个项目=&gt;在两个轴上解决。
然后用minETA增加当前时间,再试一次,直到找到的currentTime + minETA为&gt;到thisCycleTime + thisCycleDt。
如果您有兴趣,我可能会澄清一些事情。
祝你好运!