Reputation:
i need to get the touch move velocity in cocos2d. any api for this?
Upvotes: 0
Views: 3964
Reputation: 1271
The most basic way of doing this is to do the following:
Of course,register a CCLayer
with to be a touch event handler, and implement the touch begin, move and end functions.
Create in your relevant class, 2 CGPoint
variables to store the CURRENT
and PREVIOUS
touch positions. Also create 2 CCTIme
structures to store the CURRENT
and PREVIOUSLY
polled times.
Set up a schedule to update the current time (I've done this in the init of any relevant class.
i.e:
- (id)init {
if((self = [super init])) {
[self schedule:@selector(update:)];
timeCURRENT = (ccTime)0;
}
return self;
}
-(void)update:(ccTime)deltaTime {
timeCURRENT += deltaTime;
}
4 . at the start of touch begin, set both the previous and current variables to the current touch location using the following:
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
touchCURRENT= [touch locationInView: [touch view]];
touchPREVIOUS = touchCURRENT;
timePREVIOUS = timeCURRENT;
...
Then, in touch moved, set the PREVIOUS to the CURRENT, and set the CURRENT using the same line of code as above
-(BOOL)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
touchPREVIOUS = touchCURRENT;
touchCURRENT= [touch locationInView: [touch view]];
CGPoint deltaPosition = touchCURRENT - touchPREVIOUS;
ccTime deltaTime = timeCURRENT - timePREVIOUS;
timePREVIOUS = timeCURRENT;
Velocity = deltaPosition/deltaTime.
Note that CGPoint
subtraction may not work as advertised above, you may have to subtract individual members and feed them into a CGPoint
factory method.
Upvotes: 2