在对cocos2d的sprite处理移动的过程中,通常用到的两种移动的算法:

假设这个CCNode是直接放在CCLayer上的

距离差法:

CGPoint curTouchPosUI = [touch locationInView:[touch view]];
CGPoint preTouchPosUI = [touch previousLocationInView:[touch view]]; CGPoint curTouchPosGL = [[CCDirector sharedDirector] convertToGL:curTouchPosUI]; CGPoint preTouchPosGL = [[CCDirector sharedDirector] convertToGL:preTouchPosUI]; CGPoint distancePos = ccpSub(curTouchPosGL,preTouchPosGL); self.position=ccpAdd(self.position,distancePos);

点击法:

CGPoint touchPosUI = [touch locationInView:[touch view]];
CGPoint touchPosGL = [[CCDirector sharedDirector] convertToGL:touchPosUI]; CGPoint pos = ccp(touchPosGL.x -_touchBeginPosToSelfAnchorPointDistancePos.x,
touchPosGL.y - _touchBeginPosToSelfAnchorPointDistancePos.y); self.position = pos;

其中 _touchBeginPosToSelfAnchorPointDistancePos = ccpSub(_touchBeginPos,self.position)
     
_touchBeginPos begin touch在物体上的坐标

04-18 16:52