2

我试图在 touchesbegan 方法中有多个对象(2 UIImageViews)

我正在使用以下代码,但无法正常工作。没有错误,但位置只是搞砸了。我应该怎么做?

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    UITouch *touch = [[event allTouches] anyObject];

    if (image1.image == [UIImage imageNamed:@"ball.png"]){
         CGPoint location = [touch locationInView:touch.view];
         image1.center = location;
    }
    if (image1.image == [UIImage imageNamed:@"ball2.png"]){
         CGPoint location = [touch locationInView:touch.view];
         image2.center = location;
    }
}
4

2 回答 2

2

如果你想在 touchesbegen 中识别两个图像视图,试试这个

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event //here enable the touch       
 {
// get touch event


UITouch *touch = [[event allTouches] anyObject];

CGPoint touchLocation = [touch locationInView:self.view];
if (CGRectContainsPoint(image1.frame, touchLocation))
{
    NSLog(@"image1 touched");
    //Your logic
}
if (CGRectContainsPoint(image2.frame, touchLocation))
{
    NSLog(@"image2 touched");
            //your logic
}
     }

希望这有帮助

于 2011-02-10T05:21:56.603 回答
0

我想,如果你需要越过一圈和中心,image1.image在你的第二种if情况下需要。但是,如果您需要移动图像,则必须执行以下操作 -image2.imageimage1image2

  1. 检查触摸点是否属于两个对象。
  2. 如果是,则将两个图像相对移动。(即,将移动量添加到较早的图像中心)。不将触摸点作为图像中心位置。

例如:如果image1中心在 (x1, y1) 并且image2中心在 (x2, y2)。现在接触点 (x3, y3) 既属于 imageimage1又属于image2. 如果新拖动在(x4,y4),则拖动量分别为x4-x3y4-y3沿x,y方向。将此拖动量添加到图像的中心,以使图像出现在新位置。


伪代码

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];

    float touchXBeginPoint = [touch locationInView:touch.view].x;
    float touchYBeginPoint = [touch locationInView:touch.view].y;

    // Now Check touchXBeginPoint, touchYBeginPoint lies in image1, image2
    // Calculate the offset distance.

    if( /* both are true */ )
    {

       // Add the offset amount to the image1, image2 center.

    }

    else if( /* image1 touch is true */ )
    {
         // Add the offset amount to the image1 center
    }

    else if( /* image2 touch is true */ )
    {
         // Add the offset amount to the image2 center
    }
}

下载iPhone Game Dev第 3 章的源代码,看看图像是如何移动的。

于 2011-02-10T04:45:56.593 回答