Box2D/Cocos2D: Errors in CreateFixture - objective-c

i'm programming a little game. you can shoot little bullets which should disappear when hitting an object. the problem is when i destroy the bodies (directly or first storing them into an array) i get errors within the CreateFixture() function for creating new bullets.
The code:
-(void)tick:(ccTime)deltaTime {
if(canShoot)
[self performPistol];
[self updatePositions:deltaTime];
[self collisionDetection];
}
-(void)updatePositions:(ccTime)deltaTime {
int32 velocityIterations = 8;
int32 positionIterations = 1;
world->Step(deltaTime, velocityIterations, positionIterations);
for(id object in _objectsToDelete) {
b2Body *body = (b2Body*)[object pointerValue];
[self removeChild:((CCSprite*)body->GetUserData()) cleanup:YES];
world->DestroyBody((b2Body*)[object pointerValue]);
}
[_objectsToDelete removeAllObjects];
}
-(void)collisionDetection {
for (b2Contact* c = world->GetContactList(); c; c = c->GetNext()) {
b2Body *a = c->GetFixtureA()->GetBody();
b2Body *b = c->GetFixtureB()->GetBody();
CCSprite *aSprite = (CCSprite*)a->GetUserData();
CCSprite *bSprite = (CCSprite*)b->GetUserData();
if([[aSprite class] isSubclassOfClass:[Bullet class]]) {
if([[bSprite class] isSubclassOfClass:[Zombie class]]) {
Zombie *myZombie = (Zombie*)bSprite;
myZombie.hp -= [(Bullet*)aSprite strength];
if(myZombie.hp <= 0) {
[_objectsToDelete addObject:[NSValue valueWithPointer:b]];
}
}
[_objectsToDelete addObject:[NSValue valueWithPointer:a]];
} else if([[bSprite class] isSubclassOfClass:[Bullet class]]) {
if([[aSprite class] isSubclassOfClass:[Zombie class]]) {
Zombie *myZombie = (Zombie*)aSprite;
myZombie.hp -= [(Bullet*)bSprite strength];
if(myZombie.hp <= 0) {
[_objectsToDelete addObject:[NSValue valueWithPointer:a]];
}
}
[_objectsToDelete addObject:[NSValue valueWithPointer:b]];
}
}
}
-(void)performPistol {
float degreeRadians = _myRotation*(M_PI/180.0);
CGPoint normalVector = ccp(cosf(degreeRadians),sinf(degreeRadians));
Bullet *bullet = [[Bullet alloc] initWithFile:#"bullet_line.png"];
bullet.strength = 1;
bullet.position = ccp(_myPosition.x+(normalVector.x*25.0),_myPosition.y+(normalVector.y*25.0));
bullet.rotation = _myRotation*(-1);
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.bullet = true;
bodyDef.position.Set(bullet.position.x/PTM_RATIO, bullet.position.y/PTM_RATIO);
bodyDef.userData = bullet;
b2Body *body = world->CreateBody(&bodyDef);
// Define another box shape for our dynamic body.
b2PolygonShape box;
box.SetAsBox(6.25/PTM_RATIO, 0.5/PTM_RATIO);
// Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &box;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
fixtureDef.filter.categoryBits = MASK_PLAYER;
fixtureDef.filter.maskBits = MASK_ENEMY | MASK_WALL;
body->CreateFixture(&fixtureDef);
body->SetLinearVelocity(b2Vec2(normalVector.x*50.0,normalVector.y*50.0));
body->SetTransform(body->GetPosition(), CC_DEGREES_TO_RADIANS(-bullet.rotation));
[self addChild:bullet];
}
Why are there errors in the CreateFixture() function. end not always the same sometimes an assert error sometimes an exc_bad_access?
thanks

Related

Understanding a logic in update/add - NSUserDefaults (Objective C)

I'm writing a nice class to handle call block in NSUserDefaults.
Haven't tested it yet, but I think I miss something regarding update/add by callBlockID.
My Code:
My Code:
#implementation UserDefaultHandler
+ (UserDefaultHandler *)sharedInstance
{
static UserDefaultHandler *instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[UserDefaultHandler alloc] init];
});
return instance;
}
-(void)updateOrAddCallBlock:(NSMutableDictionary*)callBlockObject
{
NSString *callBlockID = [callBlockObject objectForKey:#"callBlockID"];
BOOL needToUpdate = NO;
NSInteger indexDict = 0;
NSMutableArray *arrayOfAllCallBlock = [[NSMutableArray alloc] init];
arrayOfAllCallBlock = (NSMutableArray*)[[NSUserDefaults standardUserDefaults] objectForKey:#"arrayOfAllCallBlock"];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
if (arrayOfAllCallBlock.count <= 0 || arrayOfAllCallBlock == nil)
{
[arrayOfAllCallBlock addObject:callBlockObject];
}
else
{
for (int i = 0; i < arrayOfAllCallBlock.count; i++)
{
NSMutableDictionary *mutableDict = [arrayOfAllCallBlock objectAtIndex:i];
NSString *idFromDict = [mutableDict objectForKey:#"callBlockID"];
if ([idFromDict isEqualToString:callBlockID])
{
needToUpdate = YES;
indexDict = i;
newDict = mutableDict;
}
}
if (needToUpdate)
{
[arrayOfAllCallBlock removeObjectAtIndex:indexDict];
[arrayOfAllCallBlock insertObject:newDict atIndex:indexDict];
}
else
{
[arrayOfAllCallBlock addObject:callBlockObject];
}
}
[self saveGlobalDict:arrayOfAllCallBlock];
}
- (NSMutableDictionary *)getCallBlockByID:(NSString*)callBlockID
{
NSMutableArray *arrayOfAllCallBlock = (NSMutableArray*)[[NSUserDefaults standardUserDefaults] objectForKey:#"arrayOfAllCallBlock"];
BOOL isFound = NO;
NSInteger indexDict = 0;
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
for (int i = 0; i < arrayOfAllCallBlock.count; i++)
{
NSMutableDictionary *mutableDict = [arrayOfAllCallBlock objectAtIndex:i];
NSString *idFromDict = [mutableDict objectForKey:#"callBlockID"];
if ([idFromDict isEqualToString:callBlockID])
{
isFound = YES;
indexDict = i;
newDict = mutableDict;
}
}
if (isFound)
{
return newDict;
}
else
{
return nil;
}
}
- (NSMutableArray*)getAllCallBlock
{
NSMutableArray *arrayOfAllCallBlock = (NSMutableArray*)[[NSUserDefaults standardUserDefaults] objectForKey:#"arrayOfAllCallBlock"];
return arrayOfAllCallBlock;
}
- (void)clearCallBlockDB
{
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"arrayOfAllCallBlock"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)saveGlobalDict:(NSMutableArray*)globalArray
{
self.globalArray = [[NSMutableArray alloc] init];
self.globalArray = globalArray;
[self clearCallBlockDB];
[[NSUserDefaults standardUserDefaults] setObject:self.globalArray forKey:#"arrayOfAllCallBlock"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)clearSingleCallBlock:(NSString*)callBlockID
{
NSMutableArray *array = [[NSMutableArray alloc] init];
array = [self getAllCallBlock];
NSMutableDictionary *specificDict = [[NSMutableDictionary alloc] init];
NSInteger getIndex = [self getIndexForCallBlock:array specificDict:specificDict];
[array removeObjectAtIndex:getIndex];
[self saveGlobalDict:array];
}
- (NSInteger)getIndexForCallBlock:(NSMutableArray*)arrayOfAllCallBlock specificDict:(NSMutableDictionary*)specificDict
{
NSInteger getIndex = 0;
for (int i = 0; i < arrayOfAllCallBlock.count; i++)
{
NSMutableDictionary *mutableDict = [arrayOfAllCallBlock objectAtIndex:i];
NSDictionary *dict_one = [specificDict copy];
NSDictionary *dict_two = [mutableDict copy];
if ([dict_two isEqualToDictionary:dict_one])
{
getIndex = i;
}
}
return getIndex;
}
#end
I'll explain: I've a UITableView and when I add a row to it, I've a new window to put details, save and present back in UITableView.
Also, I've an edit button so I can edit and update a row in the table.
Adding a row to table create a unique string (callBlockID).
I'm not sure how to handle it and whether or not my code is enough.
Any ideas?

EXC_BAD_ACCESS Error for type NSString

I'm new to this mac application development.
The app is working fine for some data and the app crashes for few entries.
-(void)presentClientsss
{
[productVendorTextField setStringValue:[NSString stringWithFormat:#"%#", [[popUpVendor selectedItem] title]]];
NSMenuItem *tempMenuItem = [popUpVendor selectedItem];
NSString *selectedItemTitle = [tempMenuItem title];
for (int k = 0; k < [appDelegate.vendorInfoArr count]; k++)
{
VendorInfo *tempCustomerInfoModel = [appDelegate.vendorInfoArr objectAtIndex:k];
if ([tempCustomerInfoModel.vendorName isEqualToString:selectedItemTitle])
{
oldVendorIde = [NSString stringWithFormat:#"%ld", tempCustomerInfoModel.rowId];
NSLog(#"Selected RowID = %#",oldVendorIde);
break;
}
}
}
I'm sending the oldVendorIdestring to next method.
- (ItemModel *)itemNodelWithAttributes {
isProductIdExist = NO;
if ([senderInfo isEqualToString:#"nP"]) {
for (int i = 0; i < [appDelegate.itemsArr count]; i++) {
ItemModel *tempIM = [appDelegate.itemsArr objectAtIndex:i];
if ([tempIM.productId isEqualToString:[[productIdTextField stringValue] uppercaseString]]) {
isProductIdExist = YES;
break;
}
}
}
if ([senderInfo isEqualToString:#"eP"]) {
for (int i = 0; i < [appDelegate.itemsArr count]; i++) {
ItemModel *tempIM = [appDelegate.itemsArr objectAtIndex:i];
if (tempIM.itemId == itemIdentity) {
if ([tempIM.productId isEqualToString:[[productIdTextField stringValue] uppercaseString]]) {
isProductIdExist = NO;
}
}
else if ([tempIM.productId isEqualToString:[[productIdTextField stringValue] uppercaseString]]) {
isProductIdExist = YES;
}
}
}
int tempItemExists = [self saveProductImage:[[productIdTextField stringValue] uppercaseString]];
NSLog(#"oldVendorIde =%#",oldVendorIde);
ItemModel *iM = [[ItemModel alloc] initWithItemId:itemIdentity defaultItemMinimumValue:[productMinValueTextField floatValue] staticItemPrice:[productPriceTextField doubleValue] dynamicItemQuantity:[productCurrentStockTextField doubleValue] staticItemDescription:[productDescriptionTextField stringValue] prodId:[[productIdTextField stringValue] uppercaseString] itemVendor:oldVendorIde itemImgExists:tempItemExists stockAvailable:0 itemNotes:[notesTextField string] BarcodeDesc:[BarcodeDescTextView stringValue]];
return iM;
}
In this method the same oldVendorIde is working fine for some data and some time it gets crashed at this point.
The oldVendorIde sometime doesnot get any value in itemNodelWithAttributes method and the app crashes at that point.
Can Sone help me to solve the issue.. Thanks in advance..
The text from a UITextField is accessed through the text property ([productIdTextField text]), not through stringValue.

Core-Plot unable to plot multiple graphs on one page (iPad)

I am trying to display multiple chart's on one screen but i am not able to get it to work. I am trying to get to a point where i have 3 x pieGraphs and 1 x scattered graph on this display.
I have tried: Unable to have two CorePlot graphs show simultaneously but not been able to solve this. I am using the example app from Core-Plot as a base for the design of the code. I see no difference when i try to emulate the solution to that problem in my code.
I am able to display the first pie chart: "matchPieChart" but not the second one "questionsPieChart". It does not look like it even process the second chart.
Without consideration of the other similar problem solution (above) the result is:
The legend on the right side is the one that is associated with the pie that is displayed to the left, i guess it hook up to the second pie that i try to display. It is displayed where the second pie chart should be displayed.
Here is the code execution, see the NSLog in the code:
iPad_matchPieChartConfiguration
numberOfRecordsForPlot:
numberOfRecordsForPlot:
numberForPlot:
numberForPlot:
numberOfRecordsForPlot:
numberOfRecordsForPlot:
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
iPad_questionsPieChartConfiguration
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
dataLabelForPlot:
dataLabelForPlot: matchPieChart
dataLabelForPlot:
dataLabelForPlot: matchPieChart
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
And here is the actual code:
-(void)iPad_matchPieChartConfiguration {
NSLog(#"iPad_matchPieChartConfiguration");
// Set titles
playerName_label.text = playerName;
myString = [[NSString alloc]initWithFormat:#"Total number of Games played: %.0f", nrGamesPlayed];
title_Matches_label.text = myString;
//Create host view
matchChartView = [[CPTGraphHostingView alloc] initWithFrame:[[UIScreen mainScreen]bounds]];
[self.view addSubview:matchChartView];
matchPieGraph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
matchChartView.hostedGraph = matchPieGraph;
matchPieGraph.plotAreaFrame.masksToBorder = NO;
matchPieGraph.paddingLeft = 10.0;
matchPieGraph.paddingTop = 120.0;
matchPieGraph.paddingRight = 350.0;
matchPieGraph.paddingBottom = 360.0;
matchPieGraph.axisSet = nil;
//====ADD MATCH PIE CHART====//
matchPiePlot = [[CPTPieChart alloc]init];
matchPiePlot.dataSource = self;
matchPiePlot.pieRadius = 100.0;
matchPiePlot.identifier = #"matchPieChart";
matchPiePlot.startAngle = M_PI_4;
matchPiePlot.sliceDirection = CPTPieDirectionCounterClockwise;
matchPiePlot.borderLineStyle = [CPTLineStyle lineStyle];
matchPiePlot.labelOffset = 5.0;
matchPieGraph.titleTextStyle = whiteText;
[matchPieGraph addPlot:matchPiePlot];
// 1 - Get graph instance
CPTGraph *matchGraph = matchChartView.hostedGraph;
// 2 - Create legend
CPTLegend *theMatchLegend = [CPTLegend legendWithGraph:matchGraph];
// 3 - Configure legen
CPTMutableTextStyle *legendMatchTextStyle = [CPTTextStyle textStyle];
legendMatchTextStyle.fontSize = 12.0f;
legendMatchTextStyle.fontName = #"Noteworthy-Bold";
legendMatchTextStyle.color = [CPTColor whiteColor];
theMatchLegend.numberOfColumns = 2;
theMatchLegend.fill = nil;
theMatchLegend.borderLineStyle = nil;
theMatchLegend.cornerRadius = 5.0;
theMatchLegend.textStyle = legendMatchTextStyle;
// 4 - Add legend to graph
matchGraph.legend = theMatchLegend;
matchGraph.legendAnchor = CPTRectAnchorRight;
matchGraph.legendDisplacement = CGPointMake(-460.0, -10.0);
}
-(void)iPad_questionsPieChartConfiguration {
NSLog(#"iPad_questionsPieChartConfiguration");
// Set titles
playerName_label.text = playerName;
myString = [[NSString alloc]initWithFormat:#"Total number of Questions answered: %.0f", nrQuestionsAnswered];
title_Questions_label.text = myString;
//Create host view
questionsChartView = [[CPTGraphHostingView alloc] initWithFrame:[[UIScreen mainScreen]bounds]];
[self.view addSubview:questionsChartView];
questionsPieGraph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
questionsChartView.hostedGraph = matchPieGraph;
questionsPieGraph.plotAreaFrame.masksToBorder = NO;
questionsPieGraph.paddingLeft = 10.0;
questionsPieGraph.paddingTop = 120.0;
questionsPieGraph.paddingRight = 150.0;
questionsPieGraph.paddingBottom = 360.0;
questionsPieGraph.axisSet = nil;
//====ADD MATCH PIE CHART====//
questionsPiePlot = [[CPTPieChart alloc]init];
questionsPiePlot.dataSource = self;
questionsPiePlot.pieRadius = 100.0;
questionsPiePlot.identifier = #"questionsPieChart";
questionsPiePlot.startAngle = M_PI_4;
questionsPiePlot.sliceDirection = CPTPieDirectionCounterClockwise;
questionsPiePlot.borderLineStyle = [CPTLineStyle lineStyle];
questionsPiePlot.labelOffset = 5.0;
questionsPieGraph.titleTextStyle = whiteText;
[questionsPieGraph addPlot:questionsPiePlot];
// 1 - Get graph instance
CPTGraph *questionsGraph = questionsChartView.hostedGraph;
// 2 - Create legend
CPTLegend *theQuestionsLegend = [CPTLegend legendWithGraph:questionsGraph];
// 3 - Configure legen
CPTMutableTextStyle *legendQuestionsTextStyle = [CPTTextStyle textStyle];
legendQuestionsTextStyle.fontSize = 12.0f;
legendQuestionsTextStyle.fontName = #"Noteworthy-Bold";
legendQuestionsTextStyle.color = [CPTColor whiteColor];
theQuestionsLegend.numberOfColumns = 2;
theQuestionsLegend.fill = nil;
theQuestionsLegend.borderLineStyle = nil;
theQuestionsLegend.cornerRadius = 5.0;
theQuestionsLegend.textStyle = legendQuestionsTextStyle;
// 4 - Add legend to graph
questionsGraph.legend = theQuestionsLegend;
questionsGraph.legendAnchor = CPTRectAnchorRight;
questionsGraph.legendDisplacement = CGPointMake(-160.0, -10.0);
}
- (void)viewDidLoad {
[super viewDidLoad];
playerName_label.text = playerName;
AccessPlayerData *checkPlayerDiffFunction = [AccessPlayerData new];
int diffLevel = [checkPlayerDiffFunction checkPlayersDifficultyLevel:playerName];
switch (diffLevel) {
case 1:
playerDifficulty_label.text = #"Difficuly Level: Children / Easy";
break;
case 2:
playerDifficulty_label.text = #"Difficuly Level : Teenager / Medium";
break;
case 3:
playerDifficulty_label.text = #"Difficuly Level: Adult / Hard";
break;
default:
break;
}
nrGamesPlayed_label.text = [NSString stringWithFormat:#"Total number of games played: %.0f", nrGamesPlayed];
//====IF THIS IS IPAD PROCESS ALL GRAPHS====//
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
double nrOfSingleGames = nrGamesPlayed -(nrGamesWon + nrGamesLost);
double nrOfTotalGames = nrGamesPlayed;
double percentageNrOfSingleGames = (nrOfSingleGames / nrOfTotalGames) * 100;
double percentageNrOfMatchGames = ((nrOfTotalGames - nrOfSingleGames) / nrOfTotalGames) * 100;
NSString *singleGames = [[NSString alloc]initWithFormat:#"%.0f (%.0f%%)", nrOfSingleGames, percentageNrOfSingleGames];
NSString *matchesGames = [[NSString alloc]initWithFormat:#"%.0f (%.0f%%)", (nrOfTotalGames - nrOfSingleGames), percentageNrOfMatchGames];
//=========ADD DATA FOR MATCHES PIE GRAPH==========//
NSMutableArray *contentMatchArray = [NSMutableArray arrayWithObjects:[NSNumber numberWithDouble:nrOfSingleGames], [NSNumber numberWithDouble:(nrOfTotalGames - nrOfSingleGames)], nil];
labelMatchOrder = [[NSArray alloc]initWithObjects:singleGames, matchesGames, nil];
legendMatchOrder = [[NSArray alloc] initWithObjects:#"Single Games", #"Matches", nil];
self.dataForMatchChart = contentMatchArray;
//=========ADD DATA FOR QUESTIONS PIE GRAPH==========//
nrQuestionsWrongAnswers = nrQuestionsAnswered - nrQuestionsCorrectAnswered;
double percentageCorrectAnswers = (nrQuestionsCorrectAnswered / nrQuestionsAnswered) * 100;
double percentageWrongAnswers = (nrQuestionsWrongAnswers / nrQuestionsAnswered) * 100;
NSString *answerCorrect = [[NSString alloc]initWithFormat:#"%.0f (%.0f%%)", nrQuestionsCorrectAnswered, percentageCorrectAnswers];
NSString *answerWrong = [[NSString alloc]initWithFormat:#"%.0f (%.0f%%)", nrQuestionsWrongAnswers, percentageWrongAnswers];
playerName_label.text = playerName;
myString = [[NSString alloc]initWithFormat:#"Total number of questions answered: %.0f",nrQuestionsAnswered];
title_Questions_label.text = myString;
NSMutableArray *contentQuestionsArray = [NSMutableArray arrayWithObjects:[NSNumber numberWithDouble:nrQuestionsWrongAnswers], [NSNumber numberWithDouble:nrQuestionsCorrectAnswered], nil];
labelQuestionsOrder = [[NSArray alloc]initWithObjects:answerWrong, answerCorrect, nil];
legendQuestionsOrder = [[NSArray alloc] initWithObjects:#"Correct answers", #"Wrong answers", nil];
self.dataForQuestionsChart = contentQuestionsArray;
NSLog(#"ContentQuestionsArray: %#", contentQuestionsArray);
//====SET GLOBAL PARAMETERS FOR THE GRAPHs====//
whiteText = [CPTMutableTextStyle textStyle];
whiteText.color = [CPTColor whiteColor];
whiteText.fontSize = 14;
whiteText.fontName = #"Noteworthy-Bold";
[self iPad_matchPieChartConfiguration];
[self iPad_questionsPieChartConfiguration];
}
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSString *)legendTitleForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index {
if ( [matchPiePlot.identifier isEqual:[NSString stringWithFormat:#"matchPieChart"]] ) {
NSLog(#"legendTitleForPieChart: matchPieChart");
if (index < [legendMatchOrder count]) {
return [legendMatchOrder objectAtIndex:index];
}
}
else if ( [matchPiePlot.identifier isEqual:[NSString stringWithFormat:#"questionsPieChart"]] ) {
NSLog(#"legendTitleForPieChart: questionsPieChart");
}
return #"N/A";
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
NSLog(#"numberOfRecordsForPlot:");
if ([plot isKindOfClass:[CPTPieChart class]]) {
return [dataForMatchChart count];
}
else {
return 10; //>>>dummy
}
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSLog(#"numberForPlot:");
NSDecimalNumber *num = nil;
if ([plot isKindOfClass:[CPTPieChart class]]) {
if (index >= [dataForMatchChart count]) {
return nil;
}
if (fieldEnum == CPTPieChartFieldSliceWidth) {
num = [dataForMatchChart objectAtIndex:index];
}
else {
num = (NSDecimalNumber *) [NSDecimalNumber numberWithUnsignedInteger:index];
}
}
return num;
}
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index {
NSLog(#"dataLabelForPlot:");
CPTTextLayer *label = nil;
if ( [plot.identifier isEqual:[NSString stringWithFormat:#"matchPieChart"]] ) {
NSLog(#"dataLabelForPlot: matchPieChart");
label = [[CPTTextLayer alloc] initWithText:[labelMatchOrder objectAtIndex:index]];
CPTMutableTextStyle *textStyle = [label.textStyle mutableCopy];
matchPiePlot.labelOffset = -80;
textStyle.fontName = #"Noteworthy-Bold";
textStyle.color = [CPTColor whiteColor];
textStyle.fontSize = 16;
label.textStyle = textStyle;
return label;
}
else if ( [plot.identifier isEqual:[NSString stringWithFormat:#"matchPieChart"]] ) {
NSLog(#"dataLabelForPlot: MATCH");
}
return label;
}
//====SET COLOR FOR SLICES IN PIE GRAPH====//
-(CPTFill *)sliceFillForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index {
// For index = 0
double red1 = 222.0;
double green1 = 184.0;
double blue1 = 135.0;
float alpha1 = 0.5f;
double red2 = 155.0;
double green2 = 00.0;
double blue2 = 0.0;
float alpha2 = 0.3f;
if (index == 0) {
CPTFill *fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:red1 green:green1 blue:blue1 alpha:alpha1]];
return fill;
}
if (index == 1) {
CPTFill *fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:red2 green:green2 blue:blue2 alpha:alpha2]];
return fill;
}
return 0;
}
I am really struggling with this and would appreciate help :-)
Change this line
questionsChartView.hostedGraph = matchPieGraph;
to
questionsChartView.hostedGraph = questionsPieGraph;
Also, check how the two hosting views are laid out within their superview (self.view). Make sure both are visible and positioned correctly.

Cocos2D - Detecting collision

I am a beginner in cocos2d and im facing a problem with detecting collision for my coins.
Sometimes it works sometimes it doesn't.
So basically, im creating a game which the user (ship) have to avoid the obstacles and collect coins on the way. The collision of the obstacle works well but not for the coins.
I was thinking maybe the loops for creating many coins is the problem but im not sure.
Can anyone help?
My codes:
- (void)update:(ccTime)dt{
double curTime = CACurrentMediaTime();
if (curTime > _nextBridgeSpawn) {
float randSecs = [self randomValueBetween:3.0 andValue:5.0];
_nextBridgeSpawn = randSecs + curTime;
float randX = [self randomValueBetween:50 andValue:500];
float randDuration = [self randomValueBetween:8.0 andValue:10.0];
CCSprite *bridge = [_bridge objectAtIndex:_nextBridge];
_nextBridge++;
if (_nextBridge >= _bridge.count) _nextBridge = 0;
[bridge stopAllActions];
bridge.position = ccp(winSize.width/2, winSize.height);
bridge.visible = YES;
[bridge runAction:[CCSequence actions:
[CCMoveBy actionWithDuration:randDuration position:ccp(0, -winSize.height)],
[CCCallFuncN actionWithTarget:self selector:#selector(setInvisible:)],
nil]];
this is where i declare my coins (continued from the update method)
int randCoin = [self randomValueBetween:0 andValue:5];
_coin = [[CCArray alloc] initWithCapacity:randCoin];
for(int i = 0; i < randCoin; ++i) {
coin = [CCSprite spriteWithFile:#"coin.png"];
coin.visible = NO;
[self addChild:coin];
[_coin addObject:coin];
}
float randCoinX = [self randomValueBetween:winSize.width/5 andValue:winSize.width - (border.contentSize.width *2)];
float randCoinY = [self randomValueBetween:100 andValue:700];
float randCoinPlace = [self randomValueBetween:30 andValue:60];
for (int i = 0; i < _coin.count; ++i) {
CCSprite *coin2 = [_coin objectAtIndex:i];
coin2.position = ccp(randCoinX, (bridge.position.y + randCoinY) + (randCoinPlace *i));
coin2.visible = YES;
[coin2 runAction:[CCSequence actions:
[CCMoveBy actionWithDuration:randDuration position:ccp(0, -winSize.height-2000)],
[CCCallFuncN actionWithTarget:self selector:#selector(setInvisible:)],
nil]];
}
}
this is to check for collision (also in the update method)
for (CCSprite *bridge in _bridge) {
if (!bridge.visible) continue;
if (CGRectIntersectsRect(ship.boundingBox, bridge.boundingBox)){
bridge.visible = NO;
[ship runAction:[CCBlink actionWithDuration:1.0 blinks:5]];
}
}
}
//this is the collision for coins which only work at times
for (CCSprite *coin2 in _coin) {
if (!coin2.visible) continue;
if (CGRectIntersectsRect(ship.boundingBox, coin2.boundingBox)) {
NSLog(#"Coin collected");
coin2.visible = NO;
}
}
}
Thank you.
Why you just don't check distances?
float dist = ccpDistance(ship.position, coin2.position);
float allowedDist = ship.contentSize.width*0.5 + coin2.contentSize.width*0.5;
if (dist<allowedDist){
NSLog(#"Collision detected");
}
If your sprites are not on the same layer, these layers should have at least same positions.
what is phone in the last piece of code? you check there if it's boundingBox intersects coins one, but I cannot see it anywhere else. Another one, boundingBox will work only if your objects have the same parent, because it returns "local" rect, relatieve to it's parent
another one point is that in case of too fast movement speed of your objects it is possible, that they will pass throw each other during tick time. I mean, that one update will be called before collision, so it will not detect it and the next one will be called after collision was finished, so it will not detect it either.
I've solved my problem by creating a timer in init and call it every 10 secs to create my coins.
My codes:
-(void) createCoins:(ccTime)delta{
CGSize winSize = [CCDirector sharedDirector].winSize;
int randCoin = [self randomValueBetween:0 andValue:10];
_coin = [[CCArray alloc] initWithCapacity:randCoin];
for(int i = 0; i < randCoin; i++) {
coin = [CCSprite spriteWithFile:#"coin30p.png"];
coin.visible = NO;
[self addChild:coin];
[_coin addObject:coin];
}
float randCoinX = [self randomValueBetween:winSize.width/5 andValue:winSize.width - (border.contentSize.width *2)];
float randCoinY = [self randomValueBetween:100 andValue:700];
float randCoinPlace = [self randomValueBetween:30 andValue:60];
for (int i = 0; i < _coin.count; i++) {
CCSprite *coin2 = [_coin objectAtIndex:i];
coin2.position = ccp(randCoinX, (winSize.height + randCoinY) + (randCoinPlace *i));
coin2.visible = YES;
[coin2 runAction:[CCSequence actions:
[CCMoveBy actionWithDuration:8 position:ccp(0, -winSize.height-2000)],
[CCCallFuncN actionWithTarget:self selector:#selector(setInvisible:)],
nil]];
}
}
in the update method:
for (CCSprite *coins in _coin){
if (!coins.visible) continue;
if (CGRectIntersectsRect(phone.boundingBox, coins.boundingBox)) {
NSLog(#"Coin collected");
coins.visible = NO;
}
}
Thank you everyone for the help(:

Objective C newbie

I'm taking a class and we're working on a Calculator program. My background is in C++. I am taking a RPN calculator entry of 3 enter sqrt and need to display it as sqrt(3) in my descriptionOfProgram method, which is new, including associated property below. Here's the class so far. Search for "xcode" to find my issues. Any ideas? I'm not very good at the basic objective c classes, but I'm trying to learn. Here's a summary:
it's complaining about my boolean. I'm not sure why. I did this in a different class and it worked fine.
it's looking for a { I don't see it
it doesn't like my use of the key. I'm unclear on how to get the key's contents I think is the problem.
It wants ] but I'm not seeing why
skipped
It expected } at #end
Hope you can help! Thanks!
//
// CalculatorBrain.m
// Calculator
//
// Created by Michele Cleary on 2/25/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "CalculatorBrain.h"
#interface CalculatorBrain()
#property (nonatomic, strong) NSMutableArray *programStack;
#property (nonatomic, strong) NSDictionary *testVariable;
#property (nonatomic) BOOL numberHandledNextOperation;
- (double) convertRadianToDegree: (double) radian;
#end
#implementation CalculatorBrain
#synthesize programStack = _programStack;
#synthesize testVariable = _testVariable;
#synthesize numberHandledNextOperation = _numberHandledNextOperation;
- (NSMutableArray *)programStack
{
if (_programStack == nil) _programStack = [[NSMutableArray alloc] init];
return _programStack;
}
//- (void)setOperandStack:(NSMutableArray *)operandStack
//{
// _operandStack = operandStack;
//}
- (void)pushOperand:(double)operand
{
[self.programStack addObject:[NSNumber numberWithDouble:operand]];
}
- (double)performOperation:(NSString *)operation
{
[self.programStack addObject:operation];
return[CalculatorBrain runProgram:self.program];
}
- (id)program
{
return [self.programStack copy];
}
+ (NSString *)descriptionOfProgram:(id)program
{
self.numberHandledNextOperation = NO; //1. this is a problem with xcode: member reference type struct objc_class * is a pointer; maybe you meant to use ->
NSMutableSet * displayDescrip = [[NSMutableSet alloc] init];
for(id foundItemKey in program)
{
if ([foundItemKey isKindOfClass:[NSString class]])
//operator or variable
{
if ([foundItemKey isEqualToString:#"sin"]&&(!self.numberHandledNextOperation))
{ //2. xcode says To match this {.
NSObject *nextObj = [program objectForKey:(foundItemKey+1); //3. xcode doesn't like this: arithmetic on pointer to interface id which is not a constant size in non-fragile ABI
//[displayDescrip addObject:foundItemKey];
}
else if ([foundItemKey isEqualToString:#"cos"])
{
//[displayDescrip addObject:foundItemKey];
}
else if ([foundItemKey isEqualToString:#"sqrt"])
{
//[displayDescrip addObject:foundItemKey];
}
else if ([foundItemKey isEqualToString:#"Ï€"])
{
//[displayDescrip addObject:foundItemKey];
}
else if (![CalculatorBrain isOperationName:foundItemKey])
{
//variable
//[displayDescrip addObject:foundItemkey];
}
else if (foundItemKey isKindOfClass:[NSNumber class]) //4. xcode expected ]
{
//number
//if next object is operation
if(isOperation([program objectForKey:(foundItemKey+1)))
{
numberHandledNextOperation = YES;
if(isOperationSpecial([program objectForKey:(foundItemKey+1)))
{ //sin or cos or sqrt need parentheses
//[displayDescrip addObject:(foundItemKey+1)];
//[displayDescrip addObject:#"("];
//[displayDescrip addObject:foundItemKey];
//[displayDescrip addObject:#")"];
}
else
{ //regular operation + - / *
//[displayDescrip addObject:(foundItemKey+1)];
//[displayDescrip addObject:(foundItemKey)];
}
numberHandledNextOperation = YES;
} //if
} //else if
} //if
} //for
//not sure if I need this next thing
//NSSet * returnedVarNames = [varNames copy];
//return returnedVarNames;
return #"implement this in Assignment 2";
}
+ (double)runProgram:(id)program
{
NSMutableArray *stack;
if ([program isKindOfClass:[NSArray class]]) {
stack = [program mutableCopy];
}
return [self popOperandOffStack:stack];
}
+ (double)runProgram:(id)program usingVariableValues:(NSDictionary *)variableValues
{
NSMutableArray *stack;
if ([program isKindOfClass:[NSArray class]]) {
stack = [program mutableCopy];
}
if(variableValues)
{
int numItemsDisplayed = [stack count];
for (int count = 0; count < numItemsDisplayed; count++)
{
id foundItem = [stack objectAtIndex:count];
if ([foundItem isKindOfClass:[NSString class]])
{
NSString * var = [variableValues objectForKey:foundItem];
if(var)
{
[stack replaceObjectAtIndex:count withObject:[NSNumber numberWithDouble:[var doubleValue]]];
}
}
}
}
return [self popOperandOffStack:stack];
}
+ (double)popOperandOffStack:(NSMutableArray *)stack
{
double result = 0;
id topOfStack = [stack lastObject];
if (topOfStack) [stack removeLastObject];
if([topOfStack isKindOfClass:[NSNumber class]]){ //number
result = [topOfStack doubleValue];
}
else if ([topOfStack isKindOfClass:[NSString class]]){ //string operation
NSString *operation = topOfStack;
if ([operation isEqualToString:#"+"]) {
result = [self popOperandOffStack:stack] + [self popOperandOffStack:stack];
}else if ([operation isEqualToString:#"*"]) {
result = [self popOperandOffStack:stack] * [self popOperandOffStack:stack];
}else if ([operation isEqualToString:#"/"]) {
double divisor = [self popOperandOffStack:stack];
if (divisor)
result = [self popOperandOffStack:stack] / divisor;
}else if ([operation isEqualToString:#"-"]) {
double subtrahend = [self popOperandOffStack:stack];
result = [self popOperandOffStack:stack] - subtrahend;
}else if ([operation isEqualToString:#"sin"]) {
result = result = (sin([self popOperandOffStack:stack])); //(sin([self convertRadianToDegree:[self popOperandOffStack:stack]]));
}else if ([operation isEqualToString:#"cos"]) {
result = (cos([self popOperandOffStack:stack]));
}else if ([operation isEqualToString:#"sqrt"]) {
result = (sqrt([self popOperandOffStack:stack]));
}else if ([operation isEqualToString:#"π"]) {
result = M_PI;
}else{
result = 0;
}
}
return result;
}
+ (NSSet *)variablesUsedInProgram:(id)program
{
NSMutableSet * varNames = [[NSMutableSet alloc] init];
for(id foundItem in program)
{
if ([foundItem isKindOfClass:[NSString class]])
{
if (![CalculatorBrain isOperationName:foundItem])
{
[varNames addObject:foundItem];
}
}
}
NSSet * returnedVarNames = [varNames copy];
return returnedVarNames;
}
+ (BOOL)isOperationName:(NSString *)foundItem
{
NSSet *myOperationSet = [NSSet setWithObjects:#"sqrt", #"sin", #"cos", #"π", #"+", #"-", #"*", #"/", nil];
return([myOperationSet containsObject:(foundItem)]);
}
- (NSString *)description
{
return [NSString stringWithFormat:#"stack = %#", self.programStack];
}
-(double) convertRadianToDegree: (double) radian;
{
return M_PI*2*radian/360;
}
#end //6. xcode expected }
+ (NSString *)descriptionOfProgram:(id)program
Do you actually want descriptionOfProgram a class + method ? If yes, it is more like a static method in C++. It doesn't belong to any particular instance of a class. There is no hidden parameter of constant pointer to the current instance is passed.