Note that there are some explanatory texts on larger screens.

plurals
  1. POCocos2D-x tutorial. Target's position
    text
    copied!<p>I'm having trouble to understand the math behind a piece of code of a tutorial of cocos2d. This piece of code is about getting the target's position of a bullet</p> <pre><code>void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event) { // Choose one of the touches to work with CCTouch* touch = (CCTouch*)( touches-&gt;anyObject() ); CCPoint location = touch-&gt;getLocationInView(); location = CCDirector::sharedDirector()-&gt;convertToGL(location); // Set up initial location of projectile CCSize winSize = CCDirector::sharedDirector()-&gt;getWinSize(); CCSprite *projectile = CCSprite::create("Projectile.png", CCRectMake(0, 0, 20, 20)); projectile-&gt;setPosition( ccp(20, winSize.height/2) ); // Determinie offset of location to projectile int offX = location.x - projectile-&gt;getPosition().x; int offY = location.y - projectile-&gt;getPosition().y; // Bail out if we are shooting down or backwards if (offX &lt;= 0) return; // Ok to add now - we've double checked position this-&gt;addChild(projectile); // Determine where we wish to shoot the projectile to int realX = winSize.width + (projectile-&gt;getContentSize().width/2); float ratio = (float)offY / (float)offX; int realY = (realX * ratio) + projectile-&gt;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-&gt;getPosition().x; int offRealY = realY - projectile-&gt;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-&gt;runAction( CCSequence::create( CCMoveTo::create(realMoveDuration, realDest), CCCallFuncN::create(this, callfuncN_selector(HelloWorld::spriteMoveFinished)), NULL) ); // Add to projectiles array projectile-&gt;setTag(2); _projectiles-&gt;addObject(projectile); } </code></pre> <p>What I don't understand is the calculation of 'realY'. It looks like that it multiplies'ratio' as a tangent.</p> <p>Thanks very much in advance</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload