Cocos2d 2.0 draw method errors - objective-c

I use cocos2d 2.0. I get an error: property 'world' not found on object of type 'ColoredCircleSprite *' What I wrote wrong in the draw method?
-(void) draw
{
[super draw];
ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
kmGLPushMatrix();
self.world->DrawDebugData();
kmGLPopMatrix();
}
I tried to do as there shown: Cocos2D 2.0 OpenGL errors?
Also I saw another way to do draw method, I must delete self. from self.world->DrawDebugData(); line and if I do that I get another error: Use undeclared identifier 'world'.
That is ColoredCircleSprite.h code:
#import "cocos2d.h"
#interface ColoredCircleSprite : CCNode <CCRGBAProtocol, CCBlendProtocol> {
float radius_;
GLubyte opacity_;
ccColor3B color_;
NSUInteger numberOfSegments;
GLfloat *circleVertices_;
ccBlendFunc blendFunc_;
}
#property (nonatomic,readwrite) float radius;
/** Opacity: conforms to CCRGBAProtocol protocol */
#property (nonatomic,readonly) GLubyte opacity;
/** Opacity: conforms to CCRGBAProtocol protocol */
#property (nonatomic,readonly) ccColor3B color;
/** BlendFunction. Conforms to CCBlendProtocol protocol */
#property (nonatomic,readwrite) ccBlendFunc blendFunc;
/** creates a Circle with color and radius */
+ (id) circleWithColor: (ccColor4B)color radius:(GLfloat)r;
/** initializes a Circle with color and radius */
- (id) initWithColor:(ccColor4B)color radius:(GLfloat)r;
- (BOOL) containsPoint:(CGPoint)point;
#end
I just copy and paste code from cocos2d-iphone.com forum. I don't really know what variable should be there and should whether there be any variable.
Thanks.

#interface ColoredCircleSprite : CCSprite
{
b2World *mWorld;
}
#property(nonatomic,assign) b2World *world;
#end
#implementation ColoredCircleSprite
#synthesize world = mWorld;
-(void)initBox2D
{
//create world in right place...
self.world = new b2World(gravity);
}
#end

Related

Objective-C Address of property expression

I need access address of property but have problem. example code is
#interface Rectangle : NSObject
{
SDL_Rect wall;
SDL_Rect ground;
}
#property SDL_Rect wall;
#property SDL_Rect ground;
#end
#implementation Rectangle
#synthesize x;
#synthesize y;
#end
#interface Graphics : NSObject
{
int w;
int h;
}
-(void) drawSurface
#end
#implementation Graphics
-(void) drawSurface
{
Rectangle *rect = [[Rectangle alloc] init];
SDL_BlitSurface(camera, NULL, background, &rect.wall);
}
#end
&rect.x is Address of property expression requested
As the comments suggest, you cannot take the address of a property. A property is really just a promise that the object in question provides accessors for some value. The value itself may or may not even exist in an instance variable. For example, the getter for a property called fullName might generate the required value on the fly by concatenating the values of firstName and lastName properties.
Since you need to pass the address of a SDL_Rect into SDL_BlitSurface(), you could first copy the necessary property into a local variable, and then pass the address of that variable:
Rectangle *rect = [[Rectangle alloc] init];
SDL_Rect wall = rect.wall;
SDL_BlitSurface(camera, NULL, background, &wall);
If you need to preserve the value left in wall after the call to SDL_BlitSurface(), copy it back again after the call:
rect.wall = wall;
I had a similar situation with subclasses needing to access a CGAffineTransform defined in the parent class. The answer came from #orpheist's answer to this question: Get the address of an Objective-c property (which is a C struct). It does involve adding a method to your Rectangle class.
#interface Rectangle : NSObject
{
NSRect wall;
NSRect ground;
}
#property NSRect wall;
#property NSRect ground;
#end
#implementation Rectangle
#synthesize wall = _wall; //x;
#synthesize ground = _ground; //y;
- (const NSRect *) addressOfWall {
return &_wall;
}
- (const NSRect *) addressOfGround {
return &_ground;
}
+(instancetype)standardRectangle
{
Rectangle *newInstance = [[self alloc] init];
newInstance.wall = NSMakeRect(0,0, 300, 100);
newInstance.ground = NSMakeRect(0 ,0, 300, 450);
return newInstance;
}
#end
Now you can use, for instance, addressOfWall thus:
- (void)testWall
{
Rectangle *rect = [Rectangle standardRectangle];
XCTAssertEqual(100, [rect addressOfWall]->size.height);
}
Address of property expression requested that means:
#preperty (nonatomic,copy) NSString *name;
if you want to get the address of self.name. You cannot write the code like this:
NSLog (#"%p",&(self.name));
Because in fact,self.name is getter method, like this:
- (NSString *)name {
return _name;
}
so you cannot get address of method.

Assistance needed writing simple Objective-C program

I have been struggling along with an online objective-c class for a few weeks now. I'm feeling very stupid..
My latest assignment is to write a program that demonstrates a class named Circle by asking the user for the circle's radius, creating a Circle object, and then reporting the circle's area, diameter, and circumference.
We should have the following member variables:
radius: a double
pi: a double initialized to 3.14159
and the following member functions:
setRadius - a mutator function for the radius variable
getRadius - an accessor function for the radius variable
getArea - returns the area of the circle, which is calculated as: area = pi * radius * radius
getDiameter - returns the diameter of the circle, which is calculated as: diameter = radius * 2
getCircumference - returns the circumference of the circle, which is calculated as: circumference = 2 * pi * radius
The member variables of the class should be set as private.
Here is my program so far:
Main:
int main(int argc, const char * argv[])
{
#autoreleasepool {
int radius;
NSLog(#"Enter the circles radius:");
scanf ("%d", &radius);
}
return 0;
}
Interface:
#import <Foundation/Foundation.h>
//circle class
#interface circle : NSObject
{ #private
-(double) radius;
-(double) pi;
}
#property int setRadius, getRadius;
-(double) getArea;
-(double) getDiameter;
-(double) getCircumcerence;
#end
Implementation:
#import "circle.h"
#implementation circle
#synthesize setRadius, getRadius;
-(double) pi
{
pi = 3.14159;
}
-(double) getArea
{
pi * radius * radius;
}
-(double) getDiameter
{
radius * 2;
}
-(double) getCircumcerence
{
2 * pi * radius;
}
#end
As you can see, I haven't gotten very far. I am confused as how to simply utilize my methods in my main, and am sure I have already made mistakes.
Any advice is appreciated! I really need help, and am short on time.
Also, this may be far-fetched but if anyone could maybe skype with me and help me through it?
Thanks!
As a starting point, you should set up your .h to something more like this:
#interface Circle : NSObject
#property double radius;
#property (readonly) double area;
#property (readonly) double diameter;
#property (readonly) double circumference;
#property (readonly) double pi;
-(id)initWithRadius:(double)r;
+(instancetype)circleWithRadius:(double)r;
#end
This will set up a setter and getter for radius as well as getters for area, diameter, and circumference. It also sets up an init and factory method for your circle which takes a double for the radius.
I will come back and edit in some modifications you need to make to your .m as well as your main file in order to make this work. As a note, at a minimum we'll override the getters for the 3 readonly properties. This will prevent the compiler from creating ivars (instance variables) for these properties (because we can just calculate and return the number we calculation when we call it).
In your .m:
#import Circle.h
#implementation Circle
-(id)initWithRadius:(double)r
{
self = [super init];
if(self) {
self.radius = r;
}
return self;
}
+(instancetype)circleWithRadius:(double)r
{
return [[Circle alloc] initWithRadius:r];
}
-(void)setRadius:(double)r //This method is automatically created by #property
{ //include any verification logic (make sure r>0 etc), then...
self.radius = r;
}
//we don't really need to override the radius getter
-(double)pi
{
return 3.14159; //or however much accuracy you want
}
-(double)area
{
return (self.pi * self.radius * self.radius);
}
-(double)diameter
{
return (2.0 * self.radius);
}
-(double)circumference
{
return (self.diameter * self.pi);
}
In main, you use this Circle class in just the same way you use any other object in Objective-C (think about NSString, NSArray, etc).
int main(int argc, const char * argv[])
{
#autoreleasepool {
double radius;
NSLog(#"Enter the circles radius:");
scanf ("%lf", &radius);
Circle *myCircle = [Circle circleWithRadius:radius]; //the factory method we set up
NSLog(#"myCircle radius: %lf", myCircle.radius);
NSLog(#"myCircle area: %lf", myCircle.area);
NSLog(#"myCircle diameter: %lf", myCircle.diameter);
NSLog(#"myCircle circumference: %lf", myCircle.circumference);
}
return 0;
}
There are of course many ways to set this up. I can remember being confused when starting out, below is an alternative example to give you something else to look at.
It is not intended to be fancy but just bare-bones so that you can see a minimal setup of the class with an initializer.
Note that the only value initialized is the const pi, of course, the radius can be initialized there as well, as nhgrif's example shows quite nicely.
Hope this helps!
// Circle.h
#import <Foundation/Foundation.h>
#interface Circle : NSObject
{
double radius;
double pi;
}
#property double radius, pi;
-(double) getArea;
-(double) getDiameter;
-(double) getCircumference;
#end
And then the implementation:
// Circle.m
#import "Circle.h"
#implementation Circle
#synthesize radius, pi;
// Initialize with const pi:
- (id)init {
self = [super init];
if (self) {
pi = 3.14159;
NSLog(#"Circle created.");
}
return self;
}
-(double) getArea {
return pi*radius*radius;
}
-(double) getDiameter {
return 2*radius;
}
-(double) getCircumference {
return 2*pi*radius;
}
#end
And then for main:
// main.m
#import <Foundation/Foundation.h>
#import "Circle.h"
int main(int argc, const char * argv[])
{
#autoreleasepool {
Circle *aCircle = [[Circle alloc] init];
// Use an arbitrary value:
[aCircle setRadius:2];
NSLog(#"Area = %f",[aCircle getArea]);
NSLog(#"Circumference = %f",[aCircle getCircumference]);
NSLog(#"Diameter = %f",[aCircle getDiameter]);
NSLog(#"Check pi = %f",[aCircle pi]);
}
return 0;
}

Crash when calling Block after sprite.runAction

I'm having trouble with Objective C.
I'm trying to call a block after I've moved a sprite
The short version of what i'm trying to achieve is that i want to move all of the enemies in an array, and when each one finishes moving i want to check whether it has collided.
The simplified code below shows what i'm trying to do.
My Actor class is defined like this
// -----------------------------
// Actor.h
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "ScreenObject.h"
typedef void (^actorMoveComplete)(void);
#interface Actor : ScreenObject
{
// actorMoveComplete onMoveComplete;
}
#property (nonatomic) BOOL isMoving;
#property (readwrite, copy) actorMoveComplete onMoveComplete;
#property (nonatomic, retain) CCSprite* sprite;
-(void) moveTo:(CGPoint)targetPosition Speed:(float) speed withCallback:(actorMoveComplete)moveComplete;
#end
// -----------------------------
// Actor.m
#import "Actor.h"
#implementation Actor
#synthesize onMoveComplete;
#synthesize sprite;
-(void) moveTo:(CGPoint)targetPosition Speed:(float) speed withCallback:(actorMoveComplete)moveComplete;
{
onMoveComplete = moveComplete;
id actionMove = [CCMoveTo actionWithDuration:speed position:targetPosition];
id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:#selector(spriteMoveFinished:)];
[super.sprite runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];
}
-(void) spriteMoveFinished:(id) sender
{
isMoving = NO;
if (onMoveComplete != nil)
onMoveComplete();
}
#end
As you can see i'm trying to store the block in an onMoveComplete parameter (i've also tried it in a private variable), and then call it once the sprite move has completed.
In my calling class i'm iterating through a bunch of actors (enemies) and i want to call this anonymous code block for each actor once the move has completed:
{
[self checkForCollision:enemy];
}
My calling class looks like this.
//------------------------------
//
// GameLayer.h
#import "cocos2d.h"
#import "Actor.h"
#interface GameLayer : CCLayerColor
{
}
#property (nonatomic, copy) NSMutableArray *enemies;
- (void) updateEnemies;
- (void) checkForCollision:(Actor*)actor;
- (BOOL) isMapGridClear:(CGPoint)mapGrid excludeActor:(Actor*)actor;
#end
//------------------------------
// GameLayer.m
#import "GameLayer.h"
#implementation GameLayer
#synthesize enemies;
- (void) updateEnemies
{
for (Actor *enemy in enemies)
{
//
CGPoint newPosition = [self getNewPosition:enemy]; /* method to figure out new position */
[enemy moveDelta:ccp(dX, dY) Speed:enemySpeed withCallback:^{
[self checkForCollision:enemy];
}];
}
}
- (void) checkForCollision:(Actor*)actor
{
if (![self isMapGridClear:actor.gridPosition excludeActor:actor])
{
actor.isCrashed=YES;
[actor loadSprite:self spriteImage:#"crashed.png"];
}
}
- (BOOL) isMapGridClear:(CGPoint)mapGrid excludeActor:(Actor*)actor
{
/* Actual method figures out if there was a collision */
return YES;
}
#end
Unfortunately when I call the onMoveComplete block, i keep getting an EXC_BAD_ACCESS error
Interestingly, if I try to call the block inside the moveTo method, it works (but of course i want this to trigger AFTER the movement has completed).
Can anyone help me with what i'm doing wrong. Am I even using the correct mechanism?
(Apologies for the poorly formatted, incomplete code segments)
You correctly declared your property as copy, but you are setting your instance variable directly to the address of the block without using the generated accessors. That means the block won't get copied and gets destroyed before it is called.
Assign your block using self.onMoveCompleted = moveCompleted and you will be fine.

Error with getter method in Objective-C

I am following along with a series of web tutorials relating to Objective-C and am now getting a "Accessing unknown origin getter method" error when i try to build my program (origin being a member of a Rectangle class that I created).
Here is my class titled PointXY:
#import <Foundation/Foundation.h>
#interface PointXY : NSObject
{
int x;
int y;
}
//Setters and Getters
#property int x;
#property int y;
//Methods
- (void) setXY : (int) xCO : (int) yCO;
#end
I then define a rectangle class, that has a member that is of type PointXY:
#import <Foundation/Foundation.h>
#class PointXY;
#interface rectangle : NSObject
{
float width;
float height;
PointXY * origin;
}
//Setters and Getters
#property float width, height;
//Instance Methods
- (float) getArea;
- (float) getPerimeter;
//We already have setters and getters defined for width
//and height. The below method is for illustration purposes
- (void) setHW: (float) h : (float) w;
//Methods to set and get origin values
- (PointXY *) getOrigin; //Returns a PointXY object
- (void) setOrigin : (PointXY *) point;
#end
I get the error in main, if i try to access the x or y property of my origin member via my NSLog statement:
#import <Foundation/Foundation.h>
#import "rectangle.h"
#import "PointXY.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//Create an object
rectangle * myRectangle = [[rectangle alloc]init];
PointXY * rOrigin = [[PointXY alloc]init];
[rOrigin setXY:100 :100];
myRectangle.origin = rOrigin;
NSLog(#"The origin for the rectangle is %i, %i", myRectangle.origin.x, myRectangle.origin.y);
[pool drain];
return 0;
}
I understand that one cannot access the members without either explicitly defining a synthesized accessor or by creating a method to do just that and was surprised to see the author of the tutorial do the above with no issue.
Is the above even possible? Can I access myRectangle.origin.x without origin being synthesized in myRectangle or do I have something set up incorrectly.
Thanks for your time.
Origin is an instance variable you need to create an #property for it and synthesize it as you already know.
//Setters and Getters
#property float width, height;
#property PointXY *origin;
But without the property you could access the origin by doing this rectangle->origin but that defeats the purpose of encapsulation.
Edit- origin will need to be defined as #public or #package

Objective-C getter/ setter

I'm trying to work my way through an Objective-C tutorial. In the book there is this example:
#interface
{
int width;
int height;
XYPoint *origin;
}
#property int width, height;
I thought, "hey there's no getter/setter for the XYPoint object. The code does work though." Now i'm going maybe to answer my own question :).
I thinks its because "origin" is a pointer already, and whats happening under the hood with "width" and "height", is that there is going te be created a pointer to them..
Am i right, or am i talking BS :) ??
I just dont get it. here's main:
#import "Rectangle.h"
#import "XYPoint.h"
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Rectangle *myRect = [[Rectangle alloc] init];
XYPoint *myPoint = [[XYPoint alloc] init];
[myPoint setX: 100 andY: 200];
[myRect setWidth: 5 andHeight: 8];
myRect.origin = myPoint;
NSLog (#"Rectangle w = %i, h = %i",
myRect.width, myRect.height);
NSLog (#"Origin at (%i, %i)",
myRect.origin.x, myRect.origin.y);
NSLog (#"Area = %i, Perimeter = %i",
[myRect area], [myRect perimeter]);
[myRect release];
[myPoint release];
[pool drain];
return 0;
}
And here's the Rectangle object:
#import "Rectangle.h"
#import "XYPoint.h"
#implementation Rectangle
#synthesize width, height;
-(void) setWidth: (int) w andHeight: (int) h
{
width = w;
height = h;
}
- (void) setOrigin: (XYPoint *) pt
{
origin = pt;
}
-(int) area
{
return width * height;
}
-(int) perimeter
{
return (width + height) * 2;
}
-(XYPoint *) origin
{
return origin;
}
#end
What i dont understand is this line in main: myRect.origin = myPoint; I did not make a setter for it..
BTW thanks for your fast reply's
What i dont understand is this line in main: myRect.origin = myPoint; I did not make a setter for it..
There is both a getter and a setter (collectively referred to as accessors) created for origin in the Rectangle class. If you have a look in the implementation for Rectangle, this is the getter:
-(XYPoint *) origin
{
return origin;
}
and this is the setter:
- (void) setOrigin: (XYPoint *) pt
{
origin = pt;
}
And as of Objective-C 2.0 calling:
myRect.origin = myPoint;
is equivalent to:
[myRect setOrigin:myPoint];
Declaring getters and setters using #property (and then implementing them using #synthesize) is only one way of declaring and creating accessors, and is there for a convenience if you have lots of properties to declare in the class interface. As Schildmeijer said, #property int width is equivalent to declaring two methods:
- (int)width;
- (void)setWidth:(int)newWidth;
Due to the dynamically-bound nature of Objective-C method calls, you don't even have to declare the getter and setter methods in the interface, although it is generally best practice to do so if you are advertising them as publicly available to other classes.
You can think of a property declaration as being equivalent to declaring two accessor methods. Thus
#property int width;
is equivalent to:
- (int)width;
- (void)setWidth:(int)newWidth;
//Rectangle.h
#import <Foundation/Foundation.h>
#interface Rectangle : NSObject
#property int Width;
#property int Height;
-(int)Area;
#end
//Rectangle.m
#import "Rectangle.h"
#implementation Rectangle
#synthesize Width;/*Will create value Width , Setter called"setWidth" and Getter called "Width"*/
#synthesize Height;/*Will create value Height , Setter called"setHeight" and Getter called "Height"*/
-(int)Area
{
return Width*Height;
}
#end
// main.m
#import <Cocoa/Cocoa.h>
#import "Rectangle.h"
int main(int argc, const char * argv[])
{
Rectangle *myRectangle = [Rectangle new];
myRectangle.Width=3;
myRectangle.Height=5;
printf("Area = %d\n",[myRectangle Area]);
//Or
[myRectangle setWidth:5];
[myRectangle setHeight:6];
printf("Area = %d\n",[myRectangle Area]);
}
If you want to make Getter only or rename getter and setter
• readonly
• getter = newGetterName
• setter = new SetterName
example
//Rectangle.h
#import <Foundation/Foundation.h>
#interface Rectangle : NSObject
#property (getter = getWidth) int Width;
#property (readonly) int Height;
#end
You don't say what code is working, or what your expectations are for "working".
The above interface will create simple accessor methods for width and height that can be called from other objects as [object setWidth:1]; or object.width = 1; - these two are analogous.
Origin is some other object type and is a pointer, yes. But you would still want to declare a property for it to generate accessor methods.
Getters and setters are mostly useful if you need to access an instance variable from another class or you're using bindings to get/set them. So my guess would be that you need this functionality for the width and height but not for the origin. Note that the getters/setters do not make pointers out of the integers as you stated might be the reason. Ints are ints and getters/setters do not change that.