views:

283

answers:

2

I went through this tutorial about how to animate sprites: http://icodeblog.com/2009/07/24/iphone-programming-tutorial-animating-a-game-sprite/

I've been attempting to expand on the tutorial by trying to make Ryu animate only when he is touched. However, the touch is not even being registered and I believe it has something to do with it being a subview. Here is my code:

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

 if([touch view] == ryuView){
  NSLog(@"Touch");
 } else {
  NSLog(@"No touch");
 }
}

-(void) ryuAnims{
 NSArray *imageArray = [[NSArray alloc] initWithObjects:
         [UIImage imageNamed:@"1.png"],
         [UIImage imageNamed:@"2.png"],
         [UIImage imageNamed:@"3.png"],
         [UIImage imageNamed:@"4.png"],
         [UIImage imageNamed:@"5.png"],
         [UIImage imageNamed:@"6.png"],
         [UIImage imageNamed:@"7.png"],
         [UIImage imageNamed:@"8.png"],
         [UIImage imageNamed:@"9.png"],
         [UIImage imageNamed:@"10.png"],
         [UIImage imageNamed:@"11.png"],
         [UIImage imageNamed:@"12.png"],
         nil];

 ryuView.animationImages = imageArray;
 ryuView.animationDuration = 1.1;
 [ryuView startAnimating];


}



-(void)viewDidLoad {
       [super viewDidLoad];

       UIImageView *image = [[UIImageView alloc] initWithFrame:
        CGRectMake(100, 125, 150, 130)];
 ryuView = image;


 ryuView.image = [UIImage imageNamed:@"1.png"];
 ryuView.contentMode = UIViewContentModeBottomLeft; 
 [self.view addSubview:ryuView];
        [image release];
}

This code compiles fine, however, when touching or clicking on ryu, nothing happens. I've also tried

if([touch view] == ryuView.image) 

but that gives me this error: "Comparison of distinct Objective-C type 'struct UIImage *' and 'struct UIView *' lacks a cast." What am I doing wrong?

A: 

Is the UIView set up to receive touch events at all?

ryuView.userInteractionEnabled = YES;
Shaggy Frog
A: 

touchesBegan is method of UIView class, and it should be implemented in subclass of UIView (or of UIImageView in your case). Not in some outer class where you implement animation block!

So ensure that you create subclass of UIImageView e.g. RyuImageView and implement touchesBegan method. Then you should inform your object with animation block that ryuView was touched. You can use delegate method for this. See answer http://stackoverflow.com/questions/2432176/xcode-how-to-change-image-on-touching-at-an-image-same-position/2434440#2434440 as sample.

And yes, set UIImageView's userInteractionEnabled to YES because default value of this property of UIImageView is NO

do it either in initWith... method of RyuImageView:

self.userInteractionEnabled = YES;

or in your animation block class:

 ryuView.userInteractionEnabled = YES;
Vladimir