使用矢量在目的地准确停止精灵



我希望我的精灵移动到精确的像素位置。我在更新方法中使用以下代码来移动我的精灵(kPlayerSpeed = 60.0f):

if (ccpDistance(self.position, requestedPosition) < kPlayerSpeed) {
            [self changeState:kStateWalking];
            return;
        }
switch (self.characterState) {
        case kStateWalkingUp:
            self.position = ccp(self.position.x, self.position.y + kPlayerSpeed * deltaTime);
            break;
        case kStateWalkingDown:
            self.position = ccp(self.position.x, self.position.y - kPlayerSpeed * deltaTime);
            break;
        case kStateWalkingLeft:
            self.position = ccp(self.position.x - kPlayerSpeed * deltaTime, self.position.y);
            break;
        case kStateWalkingRight:
            self.position = ccp(self.position.x + kPlayerSpeed * deltaTime, self.position.y);
            break;
        case kStateIdle:
            break;
        default:
            break;
if (ccpDistance(self.position, requestedPosition) < kPlayerSpeed)

使用此代码,玩家可以停在附近,但不完全在原地。

我会按照这些思路做一些事情。 不过还没有测试过,我是从我的GFS PC上写的。

CGPoint velocity = CGPointZero;
CGPoint delta = ccpSubstract(requestedPosition, self.position);
switch (self.characterState) {
        case kStateWalkingUp:
            velocity= ccp(0, kPlayerSpeed * deltaTime);
            break;
        case kStateWalkingDown:
            velocity = ccp(0,-kPlayerSpeed * deltaTime);
            break;
        case kStateWalkingLeft:
            velocity= ccp(-kPlayerSpeed * deltaTime, 0);
            break;
        case kStateWalkingRight:
            velocity= ccp(kPlayerSpeed * deltaTime, 0);
            break;
        case kStateIdle:
            break;
        default:
            break;
}
CGPoint signsVelocity = ccpNormalize(velocity);
CGPoint absVelocity = ccp( MIN( fabsf(velocity.x), fabsf(delta.x)) , MIN(fabsf(velocity.y), fabsf(velocity.x) );
self.position = ccpAdd(self.position, ccpMult(absVelocity, signsVelocity) );

安德烈斯,感谢您的回复。

无法完全让你的代码工作,所以利用你的领导,我做了更多的研究并想出了这个......

    float step = kPlayerSpeed * deltaTime;
    float dist = ccpDistance(self.position, requestedPosition);
    if (dist <= step) {
        self.position = requestedPosition;
    } else {
        CGPoint vectorBetweenAB = ccpSub(self.position, requestedPosition);
        CGPoint normVectorBetweenPositionAndEnd = ccpNormalize(vectorBetweenAB);
        CGPoint movementVectorForThisFrame = ccpMult(normVectorBetweenPositionAndEnd, step);
        if (self.position.x > movementVectorForThisFrame.x) {
            movementVectorForThisFrame.x = -movementVectorForThisFrame.x;
        }
        if (self.position.y > movementVectorForThisFrame.y) {
            movementVectorForThisFrame.y = -movementVectorForThisFrame.y;
        }
        self.position = ccpAdd(self.position, movementVectorForThisFrame);
    }

有没有比这更好的方法?

谢谢

相关内容

  • 没有找到相关文章

最新更新