Sorry I'm new to Objective C and OOP, and I'm trying to understand how to use classes. I have searched everywhere but can't find a clear answer.
So in my game I want a NEW ball to be created when i tap and drag an image of a ball. Would I create a ball class, and when I tap the ball, an instance of the ball class will be created. How do I set that class to be an image of a ball?
You didn't provide much detail, but i guess you will create more than one ball in some View controlled by a whateverViewController. One simple approach would be a collection class holding the balls created.
ReplyDeleteIN your whateverViewController class :
....
@property (nonatomic,retain) NSMutableSet *balls; // release in dealloc
On tap - a ball gets created and added to the set.
Your ball class then implements whatever you need for a ball and holds a UIImage for display.
....
@property (nonatomic,retain) UIImage* ballImage; // release in dealloc
You didn't explain well your game, but I see two scenarios:
ReplyDeleteYou have multiple balls in the screen and you want a new ball to appear when you tap one of these balls. The ball new ball is similar to the ball that was tapped not only in shape (image) but also similar in behavior, so if you tap this new ball another new ball will appear.
You have in your UI images of balls. These images are similar to buttons: when you tap one of them, a ball is added to the screen. This new ball has the same shape as the image that was tapped, but it does not have a similar behavior, so you can't tap this new ball to make another new ball appear. But you still can tap the image.
In the first case, all balls are instances of the class Ball. Each ball has an image that represents it, and has an action that is triggered when the ball is tapped.
@class Ball
@property UIImage *image; // This property will be used to draw the ball
- (void)imageTapped; // This method will be called when the ball it tapped. It will create a new ball.
// ...
@end
In the second case, you still have a Ball class, but it doesn't have the method imageTapped:
@class Ball
@property UIImage *image; // This property will be used to draw the ball
// ...
@end
You will also have buttons (or other UI elements) that are displayed with the same image, and when they are tapped, the call the method imageTapped to create the new ball.
Finally, note that the class Ball may have other properties (size, position, ...) and methods.
Edit
You should have an array (NSMutableArray) called balls and initialize it in the method viewDidLoad of the view delegate.
- (void)viewDidLoad
{
// ...
self.balls = [NSMutableArray array];
}
- (void)addBall
{
// create ball
[self.balls add:ball];
}
Then, every time you create a ball, you add it to the array.