0

我正在使用 Objective C 创建一个带有 Xcode 6.1 的 iOS 应用程序

我正在尝试创建代码以在碰到另一个对象时停止移动对象(字符)。我尝试使用两种方法来做到这一点,但对象似乎停止在与我设置的不同点。以下是我尝试过的两种方法。我还在 Dropbox 上放置了完整版代码的链接(链接如下)。

方法一:当物体到达特定坐标时。

//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];
}

方法二:当对象与第二个对象相交时

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

4

1 回答 1

0

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];
}
于 2015-02-06T16:06:33.490 回答