繁体   English   中英

-(void)drawRect:(CGRect)rect,绘制一个迷宫并检测其边界

[英]- (void)drawRect:(CGRect)rect , draw a maze and detect its boundary

我正在尝试实现一个迷宫游戏,该游戏将通过在drawRect开发的代码绘制自己的关卡,我只需要知道如何检测该代码将绘制的图像内容的边界,

我使用的是UIButton使用以下代码拖动是:

- (void)viewDidLoad
{
    [super viewDidLoad];
     map = [[mapView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
    [self.view addSubview:map];

    self.view.backgroundColor = [UIColor blackColor];
    meButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [meButton setTitle:@"Drag me!" forState:UIControlStateNormal];
    meButton.backgroundColor = [UIColor yellowColor];
    [meButton addTarget:self action:@selector(wasDragged:withEvent:) forControlEvents:UIControlEventTouchDragInside];

    meButton.frame = CGRectMake(100,100,50, 50);

    [self.view addSubview:meButton];
 }



- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event
{
    UITouch *touch = [[event touchesForView:button] anyObject];

    CGPoint previousLocation = [touch previousLocationInView:button];
    CGPoint location = [touch locationInView:button];
    CGFloat delta_x = location.x - previousLocation.x;
    CGFloat delta_y = location.y - previousLocation.y;

    // move button
    button.center = CGPointMake(button.center.x + delta_x,
                            button.center.y + delta_y);
    if(CGRectIntersectsRect(button.frame, map.frame)) {

        NSLog(@"CGRectIntersectsRect");

    }
}

并且此代码用于绘制地图(仍未正确实现)

- (void)drawRect:(CGRect)rect;
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 0.0, 1.0); // yellow line

    CGContextBeginPath(context);

    CGContextMoveToPoint(context, 50.0, 50.0); //start point
    CGContextAddLineToPoint(context, 250.0, 100.0);
    CGContextAddLineToPoint(context, 250.0, 350.0);
    CGContextAddLineToPoint(context, 50.0, 350.0); // end path

    CGContextClosePath(context); // close path

    CGContextSetLineWidth(context, 8.0); // this is set from now on until you explicitly change it

    CGContextStrokePath(context); // do actual stroking

    CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 0.5); // green color, half transparent
    CGContextFillRect(context, CGRectMake(20.0, 250.0, 128.0, 128.0)); // a square at the bottom left-hand corner
}

因此,您有两种方法可以真正实现这一目标。 第一种方法(我认为更难解决)是测试您当前在迷宫中的像素,并查看颜色是否对应于墙壁。 这种方法可能会出现一些细微的问题,这意味着它不是最优的。

更好的方法是将屏幕划分为一个瓷砖网格(例如10x10px),并使用它来保存迷宫的地图(例如,使用二维布尔数组)。 这样,您可以简单地查看当前所在的图块,并查看允许的移动方向。 这是处理迷宫的相当标准的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM