如何检测 UIImageView 碰撞
我想知道为什么我的代码不起作用。我希望我的球(UIImageView)从块(也是 UIImageView)上弹起。我的球将 x 和 y 运动都切换为负值,而不是仅一个。怎么了???请帮助...这是我的代码
-(void)animateBall:(NSTimer *)theTimer {
collisionCount ++;
bouncyBall.center = CGPointMake(bouncyBall.center.x + ballMovement.x, bouncyBall.center.y + ballMovement.y);
if (CGRectIntersectsRect(bouncyBall.frame, wallOne.frame)) {
if (collisionCount >= 5) {
[self processCollision:wallOne];
collisionCount = 0;
}
}
if (bouncyBall.center.x > 313 || bouncyBall.center.x < 8) {
ballMovement.x = -ballMovement.x;
}
if (bouncyBall.center.y > 453 || bouncyBall.center.y < 8) {
ballMovement.y = -ballMovement.y;
}
}
-(void)processCollision:(UIImageView *)wall {
if (ballMovement.x > 0 && wall.frame.origin.x - bouncyBall.center.x <= 4) {
ballMovement.x = -ballMovement.x;
}
else if (ballMovement.x < 0 && bouncyBall.center.x - (wall.frame.origin.x + wall.frame.size.width) <= 4) {
ballMovement.x = -ballMovement.x;
}
if (ballMovement.y > 0 && wall.frame.origin.y - bouncyBall.center.y <= 4) {
ballMovement.y = -ballMovement.y;
}
else if (ballMovement.y < 0 && bouncyBall.center.y - (wall.frame.origin.y + wall.frame.size.height) <= 4) {
ballMovement.y = -ballMovement.y;
}
}
I am wondering why my code doesn't work. I want my ball (UIImageView) to bounce off of a block (also a UIImageView). My ball switches both the x and y movements to negative instead of just one. What is wrong??? Please Help... Here is my code
-(void)animateBall:(NSTimer *)theTimer {
collisionCount ++;
bouncyBall.center = CGPointMake(bouncyBall.center.x + ballMovement.x, bouncyBall.center.y + ballMovement.y);
if (CGRectIntersectsRect(bouncyBall.frame, wallOne.frame)) {
if (collisionCount >= 5) {
[self processCollision:wallOne];
collisionCount = 0;
}
}
if (bouncyBall.center.x > 313 || bouncyBall.center.x < 8) {
ballMovement.x = -ballMovement.x;
}
if (bouncyBall.center.y > 453 || bouncyBall.center.y < 8) {
ballMovement.y = -ballMovement.y;
}
}
-(void)processCollision:(UIImageView *)wall {
if (ballMovement.x > 0 && wall.frame.origin.x - bouncyBall.center.x <= 4) {
ballMovement.x = -ballMovement.x;
}
else if (ballMovement.x < 0 && bouncyBall.center.x - (wall.frame.origin.x + wall.frame.size.width) <= 4) {
ballMovement.x = -ballMovement.x;
}
if (ballMovement.y > 0 && wall.frame.origin.y - bouncyBall.center.y <= 4) {
ballMovement.y = -ballMovement.y;
}
else if (ballMovement.y < 0 && bouncyBall.center.y - (wall.frame.origin.y + wall.frame.size.height) <= 4) {
ballMovement.y = -ballMovement.y;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
即使球击中边缘的中心也会发生这种情况吗?无论如何,您不需要一次只处理一个维度吗?第三个
if
不能是else if
吗?Does it happen even when the ball hits the center of an edge? Anyway don't you just need to handle one dimension at a time? Can't the third
if
beelse if
?