Cocos2D-x教程。目标的位置

时间:2013-09-18 13:40:55

标签: cocos2d-x

我无法理解cocos2d教程代码背后的数学知识。这段代码是关于获得目标的子弹位置

void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
    // Choose one of the touches to work with
    CCTouch* touch = (CCTouch*)( touches->anyObject() );
    CCPoint location = touch->getLocationInView();
    location = CCDirector::sharedDirector()->convertToGL(location);

    // Set up initial location of projectile
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    CCSprite *projectile = CCSprite::create("Projectile.png", CCRectMake(0, 0, 20, 20));
    projectile->setPosition( ccp(20, winSize.height/2) ); 

    // Determinie offset of location to projectile
    int offX = location.x - projectile->getPosition().x;
    int offY = location.y - projectile->getPosition().y;

    // Bail out if we are shooting down or backwards
    if (offX <= 0) return;

    // Ok to add now - we've double checked position
    this->addChild(projectile);

    // Determine where we wish to shoot the projectile to
    int realX = winSize.width + (projectile->getContentSize().width/2);
    float ratio = (float)offY / (float)offX;
    int realY = (realX * ratio) + projectile->getPosition().y;
    CCPoint realDest = ccp(realX, realY);

    // Determine the length of how far we're shooting

    // My comment: if in the next two lines we use (offX, offY) instead of (realX, realY)
    // bullet direction looks ok

    int offRealX = realX - projectile->getPosition().x;
    int offRealY = realY - projectile->getPosition().y;
    float length = sqrtf((offRealX * offRealX) + (offRealY * offRealY));
    float velocity = 480/1; // 480pixels/1sec
    float realMoveDuration = length/velocity;

    // Move projectile to actual endpoint
    projectile->runAction(  CCSequence::create( CCMoveTo::create(realMoveDuration, realDest),
                            CCCallFuncN::create(this, callfuncN_selector(HelloWorld::spriteMoveFinished)), 
                            NULL) );

    // Add to projectiles array
    projectile->setTag(2);
    _projectiles->addObject(projectile);  
}

我不明白的是'realY'的计算。它看起来像是将“比率”乘以切线。

非常感谢

1 个答案:

答案 0 :(得分:0)

这似乎与编写代码的游戏设计影响有关。

弹丸的初始位置:在屏幕中间20英寸处。也许这就是画“枪”的地方?

触摸位置:可以在任何地方。我假设触摸位置以像素报告。

偏移:在初始位置和触摸点之间画一条线。

如果用户触摸了枪的左侧(“向后”),那么我们什么都不做。

realX:无论用户在哪里触摸,我们都希望子弹在屏幕的整个宽度上移动。因此,设置我们想要达到此值的“x”坐标。

但是现在如果我们想沿着用户触摸指示的角度或轨迹发送子弹,我们需要缩放目标的Y坐标。该比率是一个比例因子,告诉我们相对于枪位置,Y必须如何改变给定的X.我们将所需的X目的地乘以该斜率,并将其添加到子弹的起点(屏幕的一半)和我们有一些“目的地”,最有可能是在屏幕外但与触摸坐标方向相同。