我正在做一个简单的游戏,用户可以将其中一个瓶子扔到顶部的状态栏上并打破它。我正在使用 touchesMoved 来测试用户是否抓住了一个瓶子(UIView),它会响应用户的手指轻弹方向而被抛出。对于投掷部分,它可以工作,但如果它抛出框架,我希望它被打破并变成一个破碎的瓶子png,这部分让人头疼。以下是部分代码:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *aTouch = [touches anyObject];
CGPoint location = [aTouch locationInView:self.view];
throwView = [self.view hitTest:location withEvent:nil];
//if the movement not on self.view, it's on the bottle.
if (bottleView != self.view) {
CGPoint loc = [aTouch locationInView:self.bottleView];
CGPoint prevloc = [aTouch previousLocationInView:self.bottleView];
//getting the finger moment
myFrame = self.bottleView.frame;
deltaX = loc.x - prevloc.x;
deltaY = loc.y - prevloc.y;
myLocation = bottleView.center;
//Here I try to multiply the finger movement to throw the bottles
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
myFrame.origin.x += deltaX*7.0;
myFrame.origin.y += deltaY*7.0;
[self.bottleView setFrame:myFrame];
[bottleView setNeedsDisplay];
[UIView commitAnimations];
//if it hits the top of the frame..
if (myFrame.origin.y <=20){
[self hitTheTop];
}
}}
//this part gives me headache, I repeat the code again otherwise the bottle is broken before hitting the top.
-(void) hitTheTop{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
myFrame.origin.x += deltaX*7.0;
myFrame.origin.y += deltaY*7.0;
[self.bottleView setFrame:myFrame];
[bottleView setNeedsDisplay];
[UIView commitAnimations];
//I calculate the slope and find where x should be when y is 0, 40 is half width of the bottle
myFrame.origin.x = myLocation.x + (myLocation.y / (-deltaY / deltaX)) - 40;
myFrame.origin.y = 0;
UIImageView *bottleBroken=
[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"broken.png"]];
[bottleBroken setFrame:CGRectMake(-20, -30, 130, 180)];
[self.bottleView setFrame:myFrame];
[bottleView addSubview:bottleBroken];
}
现在,我得到的是首先瓶子飞出框架,很短的时间,它又出现在框架的边缘并且已经破碎,看起来真的很不自然。实际上,我正在考虑将其设置为显示投掷的计时器,它可能会管理得更好。但我只是想探索是否有更简单的方法可以在没有计时器的情况下做到这一点,谢谢任何建议!