Multiple objects in touchesbegan?
I am trying to have multiple objects in a touchesbegan method (2 UIImageViews)
I am using the below code but isn't working. No errors but the location is just messed up. What should I do instead?
- (void) touchesBegan:(NSS开发者_开发知识库et*)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;
}
}
If you want to identify both image view in touchesbegen try this
-(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
}
}
Hope this help
I guess, image1.image
in your second if
condition needs to image2.image
if you need to over lap image1
and image2
center. But if you need to move the images you have to do the follow -
- Check whether the touch point belongs to both the objects.
- If yes, move both the images relatively.( i.e., add the moved amount to the earlier image center ). Not making the touch point as the image center location.
Ex: If image1
center is at (x1, y1) and image2
center is at (x2, y2). Now the touch point (x3, y3) belongs both to image image1
and image2
. If the new dragged is at (x4,y4), the drag amount is x4-x3
and y4-y3
along x,y
directions respectively. Add this drag amount to both the image's center for the image to appear at the new location.
Pseudo Code
- (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
}
}
Download the source code of iPhone Game Dev chapter 3 and see how images are being moved.
精彩评论