Question

I want to move an object from a random point just outside of the view in a Sprite Kit game.

The logical way of doing this would be to create a rectangle 100px (example) bigger than the view, and pick a random point on it's perimeter. Unfortunately, I don't know an easy way to do this.

How can I easily create a random point on the perimeter of a rectangle (which is slightly bigger than my view)?

Was it helpful?

Solution

Update

This should do what you want:

- (CGPoint)randomPointOutsideRect:(CGRect)rect withOffset:(CGFloat)offset {
    NSUInteger random = arc4random_uniform(4);
    UIRectEdge edge = 1 << random; // UIRectEdge enum values are defined with bit shifting

    CGPoint randomPoint = CGPointZero;
    if (edge == UIRectEdgeTop || edge == UIRectEdgeBottom) {
        randomPoint.x = arc4random_uniform(CGRectGetWidth(rect)) + CGRectGetMinX(rect);
        if (edge == UIRectEdgeTop) {
            randomPoint.y = CGRectGetMinY(rect) - offset;
        }
        else {
            randomPoint.y = CGRectGetMaxY(rect) + offset;
        }
    }
    else if (edge == UIRectEdgeLeft || edge == UIRectEdgeRight) {
        randomPoint.y = arc4random_uniform(CGRectGetHeight(rect)) + CGRectGetMinY(rect);
        if (edge == UIRectEdgeLeft) {
            randomPoint.x = CGRectGetMinX(rect) - offset;
        }
        else {
            randomPoint.x = CGRectGetMaxX(rect) + offset;
        }
    }

    return randomPoint;
}

This should be fairly straightforward, let me know if there's something unclear. Basically, we pick one edge at random, then "fix" one axis and pick a random value on the other (within the width/height boundaries).

arc4random_uniform gives us only integers, but that's fine because floating point values in frames are bad when displaying stuff on screen.

There is probably a shorter way to write this; feel free to edit to improve, everyone.


Original answer

How can I easily create a point 100 pixels away from the edge of my view?

With CGRectOffset().

Assuming you want a CGPoint 100pt "higher" (ie. with a lower y) than your view, do:

CGRect viewFrame = // lets say for this example that your frame is at {{20, 40}, {300, 600}}
CGRect offsetFrame = CGRectOffset(viewFrame, 0, -100);
CGPoint offsetPoint = offsetFrame.origin
// offsetPoint = {20, -60}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top