Error colliding Images method in Xcode/iOS

97 Views Asked by At

I am creating an iOS app with Xcode 6.1 using Objective C

I am trying to create code to stop a moving object (Character) when hits another object. I have tried to do this using two methods but the object seem to be stopping at a different point to what I have set it to. Below are the two methods I have tried. I have also put links to the full version of the code on dropbox (links below).

Method 1: When the object reaches a particular co-ordinate.

//Right Wall
if(Character.center.x>295){
    [CharacterMovingTimer invalidate];
}
//Left Wall
if(Character.center.x<30){
    [CharacterMovingTimer invalidate];
}
//Top Wall
if(Character.center.y<30){
    [CharacterMovingTimer invalidate];
}
//Bottom Wall
if(Character.center.y>587){
    [CharacterMovingTimer invalidate];
}

Method 2: When the object intersect with the second object

if(CGRectIntersectsRect(Character.frame, RightWall.frame)){
 [CharacterMovingTimer invalidate];
 }
 if(CGRectIntersectsRect(Character.frame, LeftWall.frame)){
 [CharacterMovingTimer invalidate];
 }
 if(CGRectIntersectsRect(Character.frame, TopWall.frame)){
 [CharacterMovingTimer invalidate];
 }
 if(CGRectIntersectsRect(Character.frame, BottomWall.frame)){
 [CharacterMovingTimer invalidate];
 }

ViewController.h https://www.dropbox.com/s/56j7rokp4il5eul/ViewController_h.rtf?dl=0

ViewController.m https://www.dropbox.com/s/faqqbsnqb8o4se7/ViewController_m.rtf?dl=0

1

There are 1 best solutions below

13
On

If you want the character to stop at 295 you would need to set their position after stopping the timer. If the character is moving at 40 pixels per timer tick the stop position could range between 295 and 335.

Using your first code as an example:

if(Character.center.x>295){
    Character.center = CGPointMake(295, Character.center.y);
    [CharacterMovingTimer invalidate];
}
//Left Wall
if(Character.center.x<30){
    Character.center = CGPointMake(30, Character.center.y);
    [CharacterMovingTimer invalidate];
}
//Top Wall
if(Character.center.y<30){
    Character.center = CGPointMake(Character.center.x, 30);
    [CharacterMovingTimer invalidate];
}
//Bottom Wall
if(Character.center.y>587){
    Character.center = CGPointMake(Character.center.x, 587);
    [CharacterMovingTimer invalidate];
}