cocos2d中两种移动的算法

本文介绍了在Cocos2d中实现Sprite移动的两种常用算法:距离差法和点击法,并提供了具体的代码示例。距离差法通过计算触摸位置的变化来更新Sprite的位置,而点击法则记录开始触摸时的位置并据此调整Sprite的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在对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在物体上的坐标

转载于:https://www.cnblogs.com/flyFreeZn/p/3427273.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值