简体   繁体   中英

swift correct syntax if else while etc

I have a SKSpritenode which can be dragged around the screen, within a boundary. I have a test for being within the boundary.

if backgroundRect.contains(paddleRect){
    let paddleX = paddle.position.x + (touchLocation.x - previousLocation.x)
    let paddleY = paddle.position.y + (touchLocation.y - previousLocation.y)
    paddle.position = CGPoint(x: paddleX, y: paddleY)
} else {
    print ("paddleRect not contained by backgroundRect")
}

At the moment I can drag the paddle around within the background. When I drag the paddle and it hits the edge of the background then it isn't contained within the background and stops so I can't move it anymore.

I would like be able to move it just within the background rectangle but not stop responding to drags at the edge. I know "if else" isn't the correct way to do this, but am wondering how I write it so the paddle keeps moving, within the bounds of the background rectangle.

Is it a "while continue" loop? or something else?

The issue is that once you exit the rectangle, you lose the ability to change the position of the paddle. Because of that, every subsequent check of backgroundRect.contains(paddleRect) will return false , forever.

What you should do instead is always compute the potential position, and either use it, or discard it:

let potentialPosition = CGPoint(
    x: paddle.position.x + (touchLocation.x - previousLocation.x),
    y: paddle.position.y + (touchLocation.y - previousLocation.y)
)

// This line is approximated, I don't know the exact relation between
// `paddleRect` and `paddle`, but you get the idea
if backgroundRect.contains(potentialPosition) {
    paddle.position = potentialPosition
} else {
    print ("paddleRect not contained by backgroundRect")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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