我有一个似乎无法解决的问题。 我想基于手指移动在屏幕上移动一个精灵,但不是让精灵向移动触摸位置,我希望精灵以相同的方式移动手指在屏幕上移动。
实施例: 用户将他/她的手指放在屏幕上(任何位置),然后将屏幕上的手指向左拖动200像素,精灵也应向左移动200像素。
我的方法是在开始时存储玩家的位置,然后计算手指的起始位置和当前位置之间的差异,以添加到精灵本身的起始位置。
这是我的代码
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
if([touches count] == 1){
UITouch *touch = [touches anyObject];
CGPoint startPos = [touch locationInView:[touch view]];
startPosition = startPos;
}
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
if([touches count] == 1){
UITouch *touch = [touches anyObject];
CGPoint touchPos = [touch locationInView:[touch view]];
CGPoint playerPos = player.position;
float yDifference = startPosition.y - touchPos.y;
playerPos.y = playerPos.y - yDifference;
// just to change to GL coordinates instead of the ones used by Cocos2D
// still doesn't work even if I remove this...
CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:playerPos];
[player setPosition:convertedPoint];
}
}
我希望我的问题很清楚,但如果不是,请不要犹豫,提出问题或进一步解释。我已经坚持了很长一段时间:'(
答案 0 :(得分:1)
此外,如果您希望它将“相对”移动到它开始的位置,而不是确切地移动到的位置:
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
if([touches count] == 1){
UITouch *touch = [touches anyObject];
CGPoint startPos = [touch locationInView:[touch view]];
startPosition = startPos;
playerStartPos = playerPos;
}
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
if([touches count] == 1){
UITouch *touch = [touches anyObject];
CGPoint touchPos = [touch locationInView:[touch view]];
CGPoint newPlayerPos;
newPlayerPos.x = playerStartPos.x + (touchPos.x - startPosition.x);
newPlayerPos.y = playerStartPos.y + (touchPos.y - startPosition.y);
// just to change to GL coordinates instead of the ones used by Cocos2D
// still doesn't work even if I remove this...
CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:newPlayerPos];
[player setPosition:convertedPoint];
}
你的代码看起来像是通过不断向playerPos.y
添加差异而“反馈”到自己身上。答案 1 :(得分:0)
所以只是不要使用差异,使用当前的触摸位置:
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
if([touches count] == 1){
UITouch *touch = [touches anyObject];
CGPoint playerPos = [touch locationInView:[touch view]];
// just to change to GL coordinates instead of the ones used by Cocos2D
// still doesn't work even if I remove this...
CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:playerPos];
[player setPosition:convertedPoint];
}