我正在开发一个棋盘游戏,我的棋盘上有10x10个单元格,每个单元格都是由UIImageView拍摄的,所以当玩家试图将一个棋子放入单元格时,应该将相应的单元格设置为图像。
我想要实现的是当用户拖动一块并尝试将其放到板上时,该块应该适合单元格的UIImageView。现在的问题是我可以把它放在板上的任何地方,甚至在两个单元之间。我该怎么办才能修复它?感谢
----------------更新:----------------
由于我在故事板中做了所有事情,所以我可以分享很少的代码。我在.h文件中有以下代码行:
@property(retain) IBOutletCollection(UIImageView) NSArray *images;
它们是一个长度为100的UIImageView数组,每个都对应一个单元格,如下所示:
电路板上当前的图标是自动生成的,我想要拖到电路板上的目标图标位于电路板的左上方(' X'图标)。以及处理拖动的以下方法:
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
现在的问题是我可以放置' X'董事会上的任何地方,如下所示:
但我想把它放到董事会的一个单元格中。
答案 0 :(得分:1)
您可以通过检测翻译结束的单元格来实现此目的。例如:
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
CGPoint origin = yourGrid.frame.origin; //where yourGrid refers to the main game board
float cellHeight = 30; //enter the corresponding value for cellHeight and cellWidth
float cellWidth = 30; //I've chosen 30 as an arbitrary value.
int translationXIndex = (recognizer.view.center.x + translation.x - origin.x)/cellWidth;
int translationYIndex = (recognizer.view.center.y + translation.y - origin.y)/cellHeight;
//Assuming you count left to right and then up to down
[[images objectAtIndex: (translationXIndex + (10*translationYIndex))] setImage:[UIImage imageNamed:@"YourImage.png"]];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
//You would have to remove the object you just dragged now, since you've changed the image of the corresponding cell
}
这是如何工作的:识别器查找翻译的中心并找出它所在的单元格。然后它访问该单元格的imageView并将图像更改为目标图像。
希望这有帮助。