嗨,我有一个物体,我可以触摸移动,但我需要它只能在一个设定区域移动,所以从:
x 0到320和 y 0到200
player.center = [myTouch locationInView:self.view];
任何想法?
这样,如果用户尝试将其移出此区域,则只会挂在外边缘。
答案 0 :(得分:0)
您可以使用MIN和MAX来约束值。
CGFloat minX = 0.0f;
CGFloat maxX = 320.0f;
CGFloat minY = 0.0f;
CGFloat maxY = 200.0f
CGPoint location = [myTouch locationInView:self.view];
CGPoint center = CGPointMake(MIN(minX, MAX(maxX, location.x)),
MIN(minY, MAX(maxY, location.y)));
player.center = center;
答案 1 :(得分:0)
你可能想做这样的事情:
CGRect validRect = CGRectMake(0.0, 0.0, 320.0, 200.0);
CGPoint touchPoint = [myTouch locationInView:self.view];
if(CGRectContainsPoint(validRect, touchPoint) {
player.center = touchPoint;
}
答案 2 :(得分:0)
这里的代码实际上非常简单,您只想检测它是否已超出边界,如果有,则更正。假设player.center
类似于NSPoint
,代码可能类似于:
if(player.center.x <= 0){
player.center.x = 0;
}else if(player.center.x >= 200){
player.center.x = 200;
}
if(player.center.y <= 0){
player.center.y = 0;
}else if(player.center.y >= 300){
player.center.y = 300;
}
如果你想让边缘不能通过边,那么你可以做一些像:
if(player.center.x - player.xSize / 2 <= 0){
player.center.x = 0 + player.xSize / 2;
}
其他x界限和y界限相同。