Move Buttons to image targets - ios

I am new in objective c and now i try to build game like What's the word and i have some problems with targets coordinates and button passing into targets. I create a -(void)dealRandomWord here I am take randome a word from plist and output all my subview on screen. I call it from viewDidLoad: [self dealRandomWord].
And here is my problem:
#pragma mark Targets
_targets = [NSMutableArray arrayWithCapacity:word1len];
for (NSInteger i = 0; i < word1len; i++) {
NSString *letter = [word1 substringWithRange:NSMakeRange(i, 1)];
TargetView *target = [[TargetView alloc] initWithLetter:letter andSideLength: letterSide];
target.center = CGPointMake(xCenterTarget + i * (letterSide + kLetterMargin), placesView.frame.size.height / 2);
[placesView addSubview:target];
NSLog(#"biiitch %#", NSStringFromCGPoint(target.center));
}
In target.center i have the coordinates of targets where i want to move my buttons by click. When i click one of the button it moved but not in the target, it happens because in
-(void)placeForButton:(InputButtonsView*)inputButtonsView atTarget:(TargetView*)targetView {
targetView.center coordinate equal {0,0}
How can i pass coordinates for each of target to my button that it's move to target. Every next button should move to next target.
Here is image: Screenshot
Thanks for any help!!!
Here is my code:
-(void)dealRandomWord {
#pragma mark Level and words init
NSAssert(self.level.words, #"Level not loaded");
// random word from plist
NSInteger randomIndex = arc4random()%[self.level.words count];
NSArray* anaPair = self.level.words[ randomIndex ];
NSString* question = anaPair[0]; // question
NSString* word1 = anaPair[1]; // answer
NSString* word2 = anaPair[2]; // some letters
NSString* helpstr = anaPair[3]; // helper
NSLog(#"qweqweq %# %# %#" , word1 , word2 , helpstr);
NSInteger word1len = [word1 length];
NSInteger word2len = [word2 length];
NSLog(#"phrase1[%li]: %#", (long)word1len, word1);
NSLog(#"phrase2[%li]: %#", (long)word2len, word2);
NSLog(#"question %#", question);
float letterSide = ceilf (kScreenWidth * 0.9 / (float)MAX(word1len, word2len) - kLetterMargin);
float xOffset = (kScreenWidth - (float)MAX(word1len, word2len) * (letterSide + kLetterMargin))/3;
xOffset += letterSide/2;
float yOffset = 1.5* letterSide;
#pragma mark QuestionView init
QuestionView *quv = [[QuestionView alloc] init];
quv.questionLabel.text = question;
[self.view addSubview:quv];
quv.center = CGPointMake(185, 210);
#pragma mark PlacesView init
PlacesView *placesView = [[PlacesView alloc] init];
[self.view addSubview:placesView];
placesView.center = CGPointMake(185, 400);
//Center x position for targets
float xCenterTarget = ((placesView.frame.size.width / 2) - ((word1len / 2) * letterSide ));
#pragma mark LetterView init
LettersView *lettersView = [[LettersView alloc] init];
[self.view addSubview:lettersView];
lettersView.center = CGPointMake(185, 500);
#pragma mark Targets
_targets = [NSMutableArray arrayWithCapacity:word1len];
for (NSInteger i = 0; i < word1len; i++) {
NSString *letter = [word1 substringWithRange:NSMakeRange(i, 1)];
TargetView *target = [[TargetView alloc] initWithLetter:letter andSideLength: letterSide];
target.center = CGPointMake(xCenterTarget + i * (letterSide + kLetterMargin), placesView.frame.size.height / 2);
[placesView addSubview:target];
NSLog(#"coord target init %#", NSStringFromCGPoint(target.center));
}
#pragma mark LettersView init
//init letters list
_letters = [NSMutableArray arrayWithCapacity: word2len];
//create letter
for (NSInteger i=0;i<word2len;i++) {
NSString* letter = [word2 substringWithRange:NSMakeRange(i, 1)];
if (![letter isEqualToString:#" "]) {
InputButtonsView *buttons = [[InputButtonsView alloc] initWithLetter:letter andSideLength:letterSide];
buttons.center = CGPointMake(xOffset + i * (letterSide + kLetterMargin), lettersView.frame.size.height /2); // "/3*4" kScreenHeight/4*3
if (i > 6) {
buttons.center = CGPointMake(- 7 * xOffset + i * (letterSide + kLetterMargin), lettersView.frame.size.height/2 + (letterSide + kLetterMargin)); // "/3*4"
}
buttons.clickDelegate = self;
[lettersView addSubview:buttons];
//[buttons addSubview:buttons];
[_letters addObject: letter];
}
}
}
-(void)inputButtonView:(InputButtonsView *)inputButtonView didPress:(CGPoint)didPress {
TargetView *targetView = nil;
NSLog(#"did press x = %f, y = %f", didPress.x , didPress.y);
for(TargetView *tv in _targets) {
if(CGRectContainsPoint(tv.frame, didPress)){
targetView = tv;
break;
}
}
[self placeForButton:inputButtonView atTarget:targetView];
if (targetView != nil) {
NSLog(#"Kek");
if ([targetView.letter isEqualToString: inputButtonView.letter]) {
[self placeForButton:inputButtonView atTarget:targetView];
}
}
}
-(void)placeForButton:(InputButtonsView*)inputButtonsView atTarget:(TargetView*)targetView {
targetView.isMatched = YES;
inputButtonsView.isMatched = YES;
inputButtonsView.userInteractionEnabled = NO;
CGPoint originButtons = [self.view.superview convertPoint:CGPointZero fromView:inputButtonsView];
CGPoint originTargets = [self.view.superview convertPoint:CGPointZero fromView:targetView];
inputButtonsView.center = originButtons;
targetView.center = originTargets;
NSLog(#"OriginButtons = %# , OriginTargets = %#", NSStringFromCGPoint(originButtons) , NSStringFromCGPoint(originTargets));
inputButtonsView.center = targetView.center;
NSLog(#"TARGETVIEW.center %#", NSStringFromCGPoint(targetView.center));
}

Related

NodesAtPoint does not find a node

I'm trying to create 10 balloons in my app. I create a random CGPoint to set my node's position and check, in case that already exist a node at this point I try again.
I don't know why, the balloons keep being placed over another balloon.
Any ideia of what I am doing wrong?
Here is my code:
-(void)gerarBaloes:(int)quantidade
{
balloons = [NSMutableArray new];
u_int32_t maxHorizontal = 900;
u_int32_t minHorizontal = 100;
u_int32_t maxVertical = 650;
u_int32_t minVertical = 100;
for (int i=1; i<= quantidade; i++) {
CGPoint posicao = CGPointMake(arc4random_uniform(maxHorizontal - minHorizontal + 1) + minHorizontal, arc4random_uniform(maxVertical - minVertical + 1) + minVertical);
while (![self validPosition:posicao]) {
posicao = CGPointMake(arc4random_uniform(maxHorizontal - minHorizontal + 1) + minHorizontal, arc4random_uniform(maxVertical - minVertical + 1) + minVertical);
}
balao* nBalao = [[balao alloc]initWithPosition:posicao];
SKLabelNode* numero = [[SKLabelNode alloc]initWithFontNamed:#"Arial Rounded MT Bold"];
numero.text = [NSString stringWithFormat:#"%d",i];
numero.zPosition = 1;
nBalao.body.zPosition = 0;
[nBalao addChild:numero];
nBalao.body.name = #"balloon";
[balloons addObject:nBalao];
[self addChild:nBalao];
}
}
And this is my validation method:
-(BOOL)validPosition:(CGPoint)position
{
NSArray* nodes = [self nodesAtPoint:position];
NSLog(#"total de nodes %d",nodes.count);
if (nodes.count > 0) {
for (SKNode* n in nodes) {
if ([n isKindOfClass:[balao class]]) {
return NO;
}
}
return YES;
}else{
return YES;
}
}
Balao.m class:
#implementation balao
-(id)initWithPosition:(CGPoint)pos
{
if (self = [super init]) {
self.position = pos;
int n = arc4random_uniform(4);
_balloonAtlas = [SKTextureAtlas atlasNamed:[NSString stringWithFormat:#"balloon%d",n]];
_explosionFrames = [NSMutableArray array];
int numImages = _balloonAtlas.textureNames.count;
for (int i=1; i<= numImages; i++){
NSString *textureName = [NSString stringWithFormat:#"balloon_%d",i];
SKTexture *temp = [_balloonAtlas textureNamed:textureName];
[_explosionFrames addObject:temp];
}
SKTexture *textInicial = [_explosionFrames[0] copy];
[_explosionFrames removeObjectAtIndex:0];
self.body = [SKSpriteNode spriteNodeWithTexture:textInicial];
[self addChild:_body];
}
return self;
}
- (void)explodeBalloon
{
SKAction* explosao = [SKAction animateWithTextures:_explosionFrames timePerFrame:0.02f resize:NO restore:YES];
[self.body runAction:explosao completion:^(void){
[self removeFromParent];
}];
[self runAction:[SKAction playSoundFileNamed:#"popSound.mp3" waitForCompletion:NO]];
}
This is how the balloons appears:
Edit:
I tried the suggested method, with CGRectCointainsPoint, but it didn't work too. :/
Checking for nodes at a given point is not enough to prevent overlap. You need to check whether the point falls inside the frame of another balloon. You can modify the function like this
-(BOOL)validPosition:(CGPoint)position
{
NSArray* nodes = [self children];
if (nodes.count > 0) {
for (SKNode* n in nodes) {
if ([n isKindOfClass:[balao class]]) {
if (CGRectContainsPoint([n getBalloonFrame], position)) // Changed line
{
return NO
}
}
}
return YES;
}
return YES;
}
CGRectContainsPoint checks whether a given rectangle contains a point.
Inside balao class define the following function. Also note the changed line in the above code.
-(void)getBalloonFrame
{
return CGRectOffset(self.body.frame, self.frame.origin.x, self.frame.origin.y)
}

How to solve the error (?memory related) on navigating between view controllers

I have two view controllers (CreateReport & ViewReport). and an NSObject class (PDFRenderer).
The infoArray(NSMutableArray)is declared as extern in PDFRenderer(NSObject class) & accessed by import # PDFRenderer.h in CreateReport class. The user selects tableview rows desired and passess the selected items to infoArray(NSMutableArray) and push ViewReport class on navigation stack to view the pdf generated using the items in the array.
CreateReport--(PDFRenderer)-->ViewReport
PROBLEM: After viewing the pdf first time without problem - now I want to navigate back to CreateReport from ViewReport - select or deselect desired table cells - update the infoArray - and push ViewReport class to see the pdf regenerated with items in updated infoArray - I am unable to pass any new changes to the infoArray(NSMutableArray). I am guessing the array is getting released or there is some memory problem. Can some one help me with this?
CreateReport.m
#import "ViewReport.h"
#import "PDFRenderer.h"
-(void)preparePDF{
//self.draftArrray has data for CreateReport tableView cells and gets updated on tableView Cells selection
NSDictionary*id_dict=[self.draftArray objectAtIndex:0];
NSArray* id_arr= [id_dict objectForKey:#"Rows"];
NSMutableArray*id_array=[[NSMutableArray alloc]init];
id_arr= [id_dict objectForKey:#"Rows"];
NSDictionary*dict=[[NSDictionary alloc]init];
for (dict in id_arr) {
NSString*id_string=[dict objectForKey:#"title"];
[id_array addObject:id_string];
}
infoArray=id_array; //pass id_array to infoArray declared in PDFRenderer
}
-(void)IBAction{
[self performSegueWithIdentifier:#"finalViewReport" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"finalViewReport"]) {
//ViewReport*destViewController = segue.destinationViewController;
[self preparePDF];
}
}
-*-
PDFRenderer.h
#import <Foundation/Foundation.h>
extern NSMutableArray*infoArray;
#interface PDFRenderer : NSObject
#property (nonatomic,strong,retain) NSMutableArray*infoArray;
+ (PDFRenderer *)sharedInstance;
-*-
PDFRenderer.m
#import "PDFRenderer.h"
NSMutableArray*infoArray;
#implementation PDFRenderer
#synthesize infoArray;
+(PDFRenderer*) sharedInstance{
static PDFRenderer* _shared = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_shared = [[self alloc] init];
_shared.infoArray = [[NSMutableArray alloc] init];
});
return _shared;
}
+ (void)drawPageNumber:(NSInteger)pageNum
{
NSString *pageString = [NSString stringWithFormat:#"Page %d", pageNum];
UIFont *theFont = [UIFont systemFontOfSize:12];
CGSize maxSize = CGSizeMake(612, 72);
CGSize pageStringSize = [pageString sizeWithFont:theFont
constrainedToSize:maxSize
lineBreakMode:NSLineBreakByClipping];
CGRect stringRect = CGRectMake(((612.0 - pageStringSize.width) / 2.0),
720.0 + ((72.0 - pageStringSize.height) / 2.0),
pageStringSize.width,
pageStringSize.height);
[pageString drawInRect:stringRect withFont:theFont];
}
+(void)drawPDF:(NSString*)fileName
{
UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil);
NSInteger currentPage = 0;
BOOL done = NO;
do {
for ( int i = 0 ; i < 4 ; i++ )
{
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
// Draw a page number at the bottom of each page.
currentPage++;
[self drawPageNumber:currentPage];
//[self drawText:#"Hello World" inFrame:CGRectMake(0, 0, 300, 50)];
int xOrigin= 50;
int yOrigin= 50;
int rowHeight = 50;
int columnWidth = 512;
int numberOfRows = 7;
int numberOfColumns = 1;
if (!i>0) {
[self drawLabels];
xOrigin= 50;
yOrigin= 300;
CGPoint from = CGPointMake(10, 60);
CGPoint to = CGPointMake(602, 60);
[PDFRenderer drawLineFromPoint:from toPoint:to];
CGPoint from1 = CGPointMake(10, 140);
CGPoint to1 = CGPointMake(602, 140);
[PDFRenderer drawLineFromPoint:from1 toPoint:to1];
}
UIGraphicsEndPDFContext();
}
+(void)drawLabels
{
int i;
NSString*s=[[NSString alloc]init];
int x=20;
int y=47;
for (i=0;i<infoArray.count;i++) {
if (i==0|i==3|i==6|i==9|i==12|i==15) {
x=20;
y+=15;
}
s=[infoArray objectAtIndex:i];
[self drawText:s inFrame:CGRectMake(x, y, 100, 25)];
x+=185;
y+=0;
}
}
-*-
ViewReport.m
-(void)viewDidLoad
{
NSString* fileName = [self getPDFFileName];
[PDFRenderer drawPDF:fileName];
NSURL *url = [NSURL fileURLWithPath:fileName];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[detailview setScalesPageToFit:YES]; //UIWebView*detailview
[detailview loadRequest:request];
//[self.view addSubview:detailview];
}
-(NSString*)getPDFFileName
{
NSString* fileName = #"newReport.PDF";
NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *path = [arrayPaths objectAtIndex:0];
NSString* pdfFileName = [path stringByAppendingPathComponent:fileName];
return pdfFileName;
}
Remove this line NSMutableArray*infoArray; Since you are using #synthesise you don't need this one.
Also, I don't see where you are using this array after all?

SHLineGraphView - Set graph origin value

Using SHLineGraphView
I want to specify the origin of my graph to a different value other than 0.
The issue was already created here Min/Max draw Y axis but the owner seems uninterested in solving it.
This is what I have now
SHLineGraphView.m
#define BOTTOM_MARGIN_TO_LEAVE 30.0
#define TOP_MARGIN_TO_LEAVE 30.0
#define INTERVAL_COUNT 10
//INTERVAL_COUNT - 3 -> Limits the y-axis to 60 but
//not the entire graph.
- (void)drawYLabels:(SHPlot *)plot {
double yRange = [_yAxisRange doubleValue]; // this value will be in dollars
double yIntervalValue = yRange / INTERVAL_COUNT;
double intervalInPx = (self.bounds.size.height - BOTTOM_MARGIN_TO_LEAVE ) / (INTERVAL_COUNT - 3);
NSLog(#"interval px %f",intervalInPx);
NSMutableArray *labelArray = [NSMutableArray array];
float maxWidth = 0;
for(int i= 0; i <= INTERVAL_COUNT - 3 ; i++){
CGPoint currentLinePoint = CGPointMake(_leftMarginToLeave, i * intervalInPx);
CGRect lableFrame = CGRectMake(0, currentLinePoint.y - (intervalInPx / 2), 100, intervalInPx);
NSLog(#"label frame %f", lableFrame.origin.y);
//if(i != 0) {
UILabel *yAxisLabel = [[UILabel alloc] initWithFrame:lableFrame];
yAxisLabel.backgroundColor = [UIColor clearColor];
yAxisLabel.font = (UIFont *)_themeAttributes[kYAxisLabelFontKey];
yAxisLabel.textColor = (UIColor *)_themeAttributes[kYAxisLabelColorKey];
yAxisLabel.textAlignment = NSTextAlignmentCenter;
float val = (yIntervalValue * (10 - i));
NSLog(#"value %f", val);
if(val > 0){
yAxisLabel.text = [NSString stringWithFormat:#"%.1i%#", (int)val, _yAxisSuffix];
} else {
yAxisLabel.text = [NSString stringWithFormat:#"%.0f", val];
}
[yAxisLabel sizeToFit];
CGRect newLabelFrame = CGRectMake(0, currentLinePoint.y - (yAxisLabel.layer.frame.size.height / 2), yAxisLabel.frame.size.width, yAxisLabel.layer.frame.size.height);
yAxisLabel.frame = newLabelFrame;
if(newLabelFrame.size.width > maxWidth) {
maxWidth = newLabelFrame.size.width;
}
[labelArray addObject:yAxisLabel];
[self addSubview:yAxisLabel];
//}
}
viewController.m
_graphView.yAxisRange = #(200);
The y-axis is ok but the graph is still plotted from origin 0.
Create a yAxisMinValue property
#property (nonatomic, strong) NSNumber *yAxisMinValue;
...and update your drawYLabels function as follows:
- (void)drawYLabels:(SHPlot *)plot {
double yRange = [_yAxisRange doubleValue]; // this value will be in dollars
double yRangeMin = [_yAxisMinValue doubleValue];
NSLog(#"yRange: %f", yRange);
NSLog(#"yRangeMin: %f", yRangeMin);
double yIntervalValue = (yRange - yRangeMin) / INTERVAL_COUNT;
NSLog(#"yIntervalValue: %f", yIntervalValue);
double intervalInPx = (self.bounds.size.height - BOTTOM_MARGIN_TO_LEAVE ) / (INTERVAL_COUNT +1);
NSMutableArray *labelArray = [NSMutableArray array];
float maxWidth = 0;
for(int i= INTERVAL_COUNT + 1; i >= 0; i--){
NSLog(#"i = %d",i);
CGPoint currentLinePoint = CGPointMake(_leftMarginToLeave, i * intervalInPx);
CGRect lableFrame = CGRectMake(0, currentLinePoint.y - (intervalInPx / 2), 100, intervalInPx);
if(i != 0) {
UILabel *yAxisLabel = [[UILabel alloc] initWithFrame:lableFrame];
yAxisLabel.backgroundColor = [UIColor clearColor];
yAxisLabel.font = (UIFont *)_themeAttributes[kYAxisLabelFontKey];
yAxisLabel.textColor = (UIColor *)_themeAttributes[kYAxisLabelColorKey];
yAxisLabel.textAlignment = NSTextAlignmentCenter;
float val = (yIntervalValue * (10 - i)) + yRangeMin;
if(val > yRangeMin){
yAxisLabel.text = [NSString stringWithFormat:#"%.1f%#", val, _yAxisSuffix];
NSLog(#"%.1f%#", val, _yAxisSuffix);
} else {
yAxisLabel.text = [NSString stringWithFormat:#"%.1f", val];
NSLog(#"%.1f", val);
}
[yAxisLabel sizeToFit];
CGRect newLabelFrame = CGRectMake(0, currentLinePoint.y - (yAxisLabel.layer.frame.size.height / 2), yAxisLabel.frame.size.width, yAxisLabel.layer.frame.size.height);
yAxisLabel.frame = newLabelFrame;
if(newLabelFrame.size.width > maxWidth) {
maxWidth = newLabelFrame.size.width;
}
[labelArray addObject:yAxisLabel];
[self addSubview:yAxisLabel];
}
}

Sprite Kit - cant get custom class data from object

I am trying to get the value from my custom class SKNode object. The problem is when I touch on the object no matter what is gives me the same value regardless of the object I touch on.
(blue button) and I cannot get the buttonID,buttonType that I set earlier.
Everything works well, except when I need to get the buttonType, buttonID of the object I touch or drag over.
I am not sure where I am going wrong, any help or push in the right direction would be great. Thanks.
here is my custom class .h file.
#import <SpriteKit/SpriteKit.h>
#interface ButtonNode : SKNode {
SKNode *buttonCustom;
}
#property int buttonType, buttonColumn, buttonID, xPos, yPos;
#property NSString *buttonName;
-(id)initWithButtonType:(int)buttonType;
#end
Here is my custom class .m file
#import "ButtonNode.h"
#define kBoxSize CGSizeMake(40, 40)
#implementation ButtonNode
#synthesize buttonColumn,buttonType,buttonID,xPos,yPos,buttonName;
static const uint32_t blueCategory = 1 << 0;
static const uint32_t redCategory = 1 << 1;
static const uint32_t greenCategory = 1 << 2;
static const uint32_t yellowCategory = 1 << 3;
-(id)initWithButtonType:(int)buttonType {
self = [super init];
if (buttonType == 1) {
NSLog(#"BLUE BUTTON CREATE");
[self addButtonBlue];
}
if (buttonType == 2) {
NSLog(#"RED BUTTON CREATE");
[self addButtonRed];
}
if (buttonType == 3) {
NSLog(#"Green BUTTON CREATE");
[self addButtonGreen];
}
if (buttonType == 4) {
NSLog(#"Yellow BUTTON CREATE");
[self addButtonYellow];
}
return self;
}
- (void) addButtonBlue {
SKSpriteNode *rect;
//button type 1
rect = [SKSpriteNode spriteNodeWithColor:[UIColor blueColor] size:kBoxSize];
int tmpInt = [[NSDate date] timeIntervalSince1970];
NSString *tmpName = [NSString stringWithFormat:#"%i", tmpInt];
rect.name = tmpName; //unique name.
rect.name = #"1";
rect.physicsBody.categoryBitMask = blueCategory;
rect.physicsBody.contactTestBitMask = blueCategory;
rect.physicsBody.collisionBitMask = blueCategory | redCategory | yellowCategory | greenCategory;
rect.position = CGPointMake(xPos , yPos );
[self addChild:rect];
}
- (void) addButtonRed {
SKSpriteNode *rect;
//button type 2
rect = [SKSpriteNode spriteNodeWithColor:[UIColor redColor] size:kBoxSize];
int tmpInt = [[NSDate date] timeIntervalSince1970];
NSString *tmpName = [NSString stringWithFormat:#"%i", tmpInt];
rect.name = tmpName; //unique name.
rect.name = #"2";
rect.physicsBody.categoryBitMask = redCategory;
rect.physicsBody.contactTestBitMask = redCategory;
rect.physicsBody.collisionBitMask = blueCategory | redCategory | yellowCategory | greenCategory;
rect.position = CGPointMake(xPos , yPos );
[self addChild:rect];
}
- (void) addButtonGreen {
SKSpriteNode *rect;
//button type 3
rect = [SKSpriteNode spriteNodeWithColor:[UIColor greenColor] size:kBoxSize];
int tmpInt = [[NSDate date] timeIntervalSince1970];
NSString *tmpName = [NSString stringWithFormat:#"%i", tmpInt];
rect.name = tmpName; //unique name.
rect.name = #"3";
rect.physicsBody.categoryBitMask = greenCategory;
rect.physicsBody.contactTestBitMask = greenCategory;
rect.physicsBody.collisionBitMask = blueCategory | redCategory | yellowCategory | greenCategory;
rect.position = CGPointMake(xPos , yPos );
[self addChild:rect];
}
- (void) addButtonYellow {
SKSpriteNode *rect;
//button type 4
rect = [SKSpriteNode spriteNodeWithColor:[UIColor yellowColor] size:kBoxSize];
int tmpInt = [[NSDate date] timeIntervalSince1970];
NSString *tmpName = [NSString stringWithFormat:#"%i", tmpInt];
rect.name = tmpName; //unique name.
rect.name = #"4";
rect.physicsBody.mass = 1;
rect.physicsBody.categoryBitMask = yellowCategory;
rect.physicsBody.contactTestBitMask = yellowCategory;
rect.physicsBody.collisionBitMask = blueCategory | redCategory | yellowCategory | greenCategory;
rect.position = CGPointMake(xPos , yPos );
[self addChild:rect];
}
#end
Here is where I create the buttons.
(at top of file with rest of global ivar )
ButtonNode * newButton;
for (int i = 1; i <= 6; i++) {
//create random Int
int tmpInt = arc4random() %3;
NSLog(#"tmp %i" ,tmpInt);
column1.position = CGPointMake(100, self.frame.size.height - 40);
if (tmpInt == 0) {
//button type 1
newButton = [[ButtonNode alloc] initWithButtonType:1];
newButton.xPos = column1.position.x;
newButton.yPos = column1.position.y *i;
newButton.buttonID = 344224351; //unique name
newButton.buttonColumn = 2;
newButton.buttonType = 1;
[column1 addChild:newButton];
blueTotal++;
totalButtons++;
column1Total++;
}
if (tmpInt == 1) {
//button type 2
newButton = [[ButtonNode alloc] initWithButtonType:2];
newButton.xPos = column1.position.x;
newButton.yPos = column1.position.y *i;
newButton.buttonID = 344224351; //unique name
newButton.buttonColumn = 2;
newButton.buttonType = 1;
[column1 addChild:newButton];
redTotal++;
totalButtons++;
column1Total++;
}
}
Here is the Part that is not working correctly.
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
for (UITouch *touch in touches) {
UITouch* touch = [touches anyObject];
CGPoint loc = [touch locationInNode:self];
NSArray *nodes = [self nodesAtPoint:loc];
for (SKNode *nod in nodes) {
NSString *tmp = nod.name;
if (tmp.length !=0) {
NSString * tmpType = nod.name;
if ([tmpType isEqualToString:#"1"]) {
NSLog(#"Node Type: %#", nod.name);
previousButton = #"1";
NSLog (#"%d",newButton.buttonType);
}
if ([tmpType isEqualToString:#"2"]) {
NSLog(#"Node Type: %#", nod.name);
previousButton = #"2";
NSLog (#"%d",newButton.buttonType);
}
if ([tmpType isEqualToString:#"3"]) {
NSLog(#"Node Type: %#", nod.name);
previousButton = #"3";
NSLog (#"%d",newButton.buttonType);
}
if ([tmpType isEqualToString:#"4"]) {
NSLog(#"Node Type: %#", nod.name);
previousButton = #"4";
NSLog (#"%d",newButton.buttonType);
}
}
}
}
}
A SKNode does not have those properties.
Try this just inside your for loop :
ButtonNode *myButton = (ButtonNode *)nod;
That will cast nod correctly as a ButtonNode, and you can use myButton like this :
NSLog(#"%d",myButton.buttonType);
Then you should be able to access the properties you have defined in the ButtonNode class.
You might only want to do that cast if you are sure it's a ButtonNode, but was just trying to help you understand why those properties would NEVER be accessible given your current code.
Also, your usage of newButton in that loop in touchesBegan is not what I think you 'think' it is. It's going to be the last button created, not the current node being stored in nod in the loop.

Accelerometer calculations resulting in inf

I have been trying to get to move an UIImageView with the accelerometer, however I have run into an issue. When I try to smooth out the data and work out the acceleration of the data from the original position, the values return infinity. I'm not really sure what I'm doing wrong!
Here's my code:
- (void)viewDidLoad {
gameObjects = [NSMutableArray arrayWithObjects: nil];
UIImageView* mainChar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[mainChar setCenter:CGPointMake(screenHeight/2, screenWidth/2)];
mainChar.image = [UIImage imageNamed:#"dot.png"];
[self.view insertSubview:mainChar atIndex:2];
[gameObjects addObject:mainChar];
mainChar = nil;
AvData = [NSMutableArray arrayWithObjects: nil];
motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 20;
[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData* accelerationData, NSError* error) {
if (defaultData == nil) {defaultData = accelerationData;}
[self accelerometerUpdate:accelerationData];
}];
}
-(void) accelerometerUpdate:(CMAccelerometerData*)aData {
//Accelerometer Smoothing
[AvData addObject:aData];
if ([AvData count] >= 20) {[AvData removeObjectAtIndex:0];}
float avX = 0;
float avY = 0;
float avZ = 0;
for (int i = 0; i < [AvData count]; i++) {
avX = avX + [[AvData objectAtIndex:i] acceleration].x;
avY = avY + [[AvData objectAtIndex:i] acceleration].y;
avZ = avZ + [[AvData objectAtIndex:i] acceleration].z;
}
avX = avX/([AvData count] - 1);
avY = avY/([AvData count] - 1);
avZ = avZ/([AvData count] - 1);
//Calculate the delta from original device acceleration value
float accX = defaultData.acceleration.x - avX;
float accY = defaultData.acceleration.y - avY;
//float accZ = defaultData.acceleration.z - avZ;
NSLog([NSString stringWithFormat:#"%f", accY]);
UIImageView* mainChar = [gameObjects objectAtIndex:0];
[mainChar setCenter:CGPointMake(mainChar.center.x + accX, mainChar.center.y + accY)];
//accX and accY are infinity for some reason, and so the image disappears!
mainChar = nil;
}
The weird thing is when I NSLog accY, it returns a proper value. What am I doing wrong?
Off the top of my head:
When you get to these lines:
avX = avX/([AvData count] - 1);
avY = avY/([AvData count] - 1);
avZ = avZ/([AvData count] - 1);
If count == 1 at that point, your code will divide by zero. I would expect that to crash, but if not, the result would be infinity or NAN. (I'd expect NAN, but it might return INF if it doesn't throw an exception. I'd need to test it or look it up to be sure.)

Resources