gpt4 book ai didi

ios - cocos2d使对象跟随触摸/手指

转载 作者:行者123 更新时间:2023-11-29 04:31:10 33 4
gpt4 key购买 nike

我用 cocos2d 制作了我的第一个应用程序,所以我在这里很新

我的第一个问题:

我不会让物体(船)跟随我的手指。

-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint location = [self convertTouchToNodeSpace: touch];
NSLog(@"location X: %f", location.x);
NSLog(@"location Y: %f", location.y);


if(startGameButtonIsPressed == YES) {
[boat runAction: [CCMoveTo actionWithDuration:1 position:location]];
}
}

它确实遵循,但并不流畅。如果我快速移动手指,它就会停止,只有当我停止时它才会跟随。

第二个问题

如何计算两点之间的距离。

CGPoint currentLocation = ccp(boat.position.x, boat.position.y);    
float distanceApart = ccpDistance(currentLocation, location);

问题是,currentLocation 在每次具有其他值的每个点上都不是恒定的......为什么?

也许是因为我有滚动背景??

最佳答案

您每秒多次调用 [boat runAction: [CCMoveTo actionWithDuration:1position:location]]; ,这会导致多个 CCMoveTo 操作同时运行。这不是cocos2d 的操作工具的设计用途。

如果您希望船以您定义的较慢速度跟随触摸,则无法将多个 CCMoveTo 操作排队以响应 ccTouchMoved:

相反,将 UITouch 对象(或 CGPointNSValue)推送到 NSMutableArray 上。然后定义一个回调函数,让您的船在每个 CCMoveTo 完成后保持移动。

示例代码:

//...defined elsewhere, e.g. your header file:
#define kBoatMoveTag 123

NSMutableArray *touchQueue; //treat the array like a queue.
//don't forget to alloc it before using.


-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint location = [self convertTouchToNodeSpace: touch];
NSLog(@"location X: %f", location.x);
NSLog(@"location Y: %f", location.y);

[touchQueue insertObject:[NSValue valueWithCGPoint:location] atIndex:0];
[self continueBoatMovement];
}

-(void)continueBoatMovement {
//if no queued point, or boat is already moving...
if(touchQueue.count < 1 || [boat getActionByTag:kBoatMoveTag]) {
return; //dont do anything
}

NSValue valueOfPt = [touchQueue lastObject];
[touchQueue removeLastObject];
CGPoint newPt = [valueOfPt CGPointValue];
float distance = ccpDistance(boat.position, newPt);
float duration = distance / boatSpeed; //you must define boatSpeed somewhere

CCMoveTo *move = [CCMoveTo actionWithDuration:duration position:newPt];

CCSequence *moveSeq = [CCSequence actionOne:move two:[CCCallFunc actionWithTarget:self selector:@selector(continueBoatMovement)]];
moveSeq.tag = kBoatMoveTag;
[boat runAction:moveSeq];
}

关于ios - cocos2d使对象跟随触摸/手指,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11726218/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com