Time for action – adding the touch events
We'll deal with onTouchBegan
first.
- In the
onTouchBegan
method, we start by updating the game state:bool GameLayer::onTouchBegan(Touch * touch, Event * event) { if (!_running) return true; if (_gameState == kGameOver) { if (_gameOver->isVisible()) _gameOver->setVisible(false); resetGame(); return true; }
- Next, we check on the value of
_canShoot
. This returnstrue
if the white ball is not moving.if (!_canShoot) return true;
- Next, we determine whether the touch is landing on the white ball. If it is, we start the game if it is not currently running yet and we make our timer visible. Here's the code to do this:
if (touch) { auto tap = touch->getLocation(); auto playerPos = _player->getPosition(); float diffx = tap.x - playerPos.x; float diffy = tap.y - playerPos.y; float diff = pow(diffx, 2) + pow(diffy, 2); if (diff < pow(BALL_RADIUS * 4, 2)) { ...