【问题标题】:How to implement a D-Pad Xcode 5 on an iPad如何在 iPad 上实现 D-Pad Xcode 5
【发布时间】:2014-09-08 16:33:18
【问题描述】:

我曾多次尝试为我的新迷宫游戏实现方向键,但在这样做时遇到了麻烦。我以 4 个 UIButtons 的样式进行操作,如果您按下一个,它会向上、向下、向左或向右移动另一个图像。我试过使用quartzcore和CAAnimation,但只知道有限的代码。

我已经声明了方法和按钮,但无法编写有效的代码。

我在做:

-(IBAction)Up:(id)sender{

CGPoint origin1 = self.Player.center;
CGPoint target1 = CGPointMake(self.Player.center.x, self.Player.center.y-124);
CABasicAnimation *bounce1 = [CABasicAnimation animationWithKeyPath:@"position.y"];
bounce1.duration = 0.1;
bounce1.fromValue = [NSNumber numberWithInt:origin1.y];
bounce1.toValue = [NSNumber numberWithInt:target1.y];
[self.Player.layer addAnimation:bounce1 forKey:@"position"];

}

幽灵向下移动,但立即弹回。我已经被难住了好几个小时了,这可能让我很生气,但请理解我的笨拙。

【问题讨论】:

    标签: ios xcode d-pad


    【解决方案1】:

    在 Core Animation 中,有两个层级:model 层之一和 presentation 层之一。表示层就是你所看到的;模型层是您经常在代码中与之交互的部分。这种分离很有价值,因为它可以让你创建隐式动画——例如设置图层的位置,它会动画到新的位置。 (但是,如果您为 position 分配一个值,您希望它是您之后立即读回的值,即使动画仍在进行中。)

    当您使用addAnimation:forKey: 时,您影响的是演示文稿,而不是模型。因此,在动画期间,您会看到 Player 层在移动,但该层“确实”仍然在您离开它的位置。动画一结束,它就会从图层中移除,因此演示文稿再次与模型匹配——您会在其原始位置看到它。

    如果你想让模型位置也改变,你需要单独改变它:

    self.player.layer.position = CGPointMake(self.player.layer.position.x, target1.y);
    

    您可以在添加动画后立即更新模型(动画完成后您会看到更改),或者使用完成块将其安排在动画结束时。 There are subtleties to consider for either approach.

    不过,通常,如果您只想为这样的特定更改设置动画,特别是对于 UIView 的主层,使用 UIView 上的隐式动画 API 会更简单:

    [UIView animateWithDuration:0.1 animations: ^{
        self.player.center = CGPointMake(self.player.center.x, target1.y);
    }];
    

    这将更新模型值并创建和运行从当前位置移动到目标位置的动画。


    顺便说一句:它有助于遵循 Cocoa 代码样式约定:仅对类名或其他类型名使用首字母大写,对变量/属性/方法名使用小写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      相关资源
      最近更新 更多