我的代码:
-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//Add a new body/atlas sprite at the touched location
for( UITouch *touch in touches ) {
CGPoint touchLocation = [touch locationInView: [touch view]];
CGPoint prevLocation = [touch previousLocationInView: [touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
prevLocation = [[CCDirector sharedDirector] convertToGL: prevLocation];
CGPoint diff = ccpSub(touchLocation,prevLocation);
[self setPosition: ccpAdd(self.position, diff)];
}
}
这段代码让我用手指移动图层。这很好。但现在我想让用户只在预定义的CGRect中移动图层。怎么做?
例如:
CGRect rect = CGRectMake(0,0,600,320);
现在只允许玩家在此矩形内移动图层。在那个例子中,他只能向左和向右移动它(在ipod触摸上)。 (直到600px)。
为实现这一目标,我需要做些什么改变?
感谢您的帮助。 祝你有愉快的一天:)
答案 0 :(得分:3)
保留一个变量来检查......例如..
distmoved = distmoved + touchlocation.x - prevlocation.x;
if(distmoved<600)
//move code
请注意,distmoved是一个浮动..
答案 1 :(得分:1)
你应该自己检查一下。在你的情况下并不难:
[self setPosition: ccpAdd(self.position, diff)];
if (self.position.x < minX)
{
//correct x position
}
if (...)
// ...
// ans so on