【问题标题】:How to determine the location of a touch using view property如何使用视图属性确定触摸的位置
【发布时间】:2011-08-17 20:29:09
【问题描述】:

我正在尝试开发一些简单的游戏应用。对于乒乓球风格的游戏,我有一个保持在界内的移动球和两个球拍。我实现了移动桨 1 的代码,以便它按预期反射球。

当我尝试将相同的行为添加到另一个桨时,我尝试了这个:

UITouch *touch = [[event allTouches]anyObject]; // Picks up the touch

CGPoint location = [touch locationInView:self.view]; // Gets coordinates 
// to help move the paddle on the X axis; Y axis is determined by the paddle,
// so it only moves along one axis


if ([touch view] == paddle2) {
    // move the second paddle 
    ...    
}

else {
    // move the first paddle   
    ...
}

但是,任何触摸都只会移动 paddle1,表明条件从未激活。根据文档,我认为通过发送[touch view] 消息,被触摸的图像视图将返回它自己的名称。 我究竟做错了什么?有更简单的方法吗?

【问题讨论】:

    标签: objective-c ios4 xcode4 interface-builder


    【解决方案1】:

    不要对桨使用不同的视图,使用具有不同 CALayers 的主机视图来绘制对象。
    您可以通过为图层分配新的原点来移动桨。 视图应处理以下方法

    - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event;
    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
    

    找出你触摸它的地方。 假设您知道桨的框架,您可以决定是否用触摸击打它们。

    我希望这会有所帮助。

    【讨论】:

    • 感谢您的建议,@Davyd。它确实看起来像是一种更优雅的方式来实现我所想到的行为。这个周末我会多看看这个,当我有更多时间的时候。现在,我找到了一个简单的解决方法,将“if”语句替换为“if (CGRectContainsPoint([paddle2 frame], [touch locationInView:self.view]))”。它似乎可以正确识别触摸,并在触摸时移动。
    • 是的,这行得通。如果您只有很少的视图,您不会注意到性能有任何差异。
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    相关资源
    最近更新 更多