Beispiel #1
0
void Entity::updatePosition(cocos2d::Vec2 pos){
    if(frameChangeCount-- < 0){
        frameChangeCount = 3;
        this->changeFrame();
    }
    
    // If the current position is (still) outside the screen no adjustments should be made!
    // This allows entities to move into the screen from outside.
    bool hasCollision = false;
    
    Rect screenRect = GameScene::getScreenRect();
    Rect boundingBox = this->boundingBox();
    boundingBox.origin.x += screenRect.origin.x;
    boundingBox.origin.y += screenRect.origin.y;
    if (screenRect.intersectsRect(boundingBox)) {
        auto screenSize = GameScene::getScreenRect().size;
        float halfWidth = this->getContentSize().width * 0.5f;
        float halfHeight = this->getContentSize().height * 0.5f;
        
        // Cap the position so the Ship's sprite stays on the screen
        if (pos.x < halfWidth){
            pos.x = halfWidth;
            
            if (dynamic_cast<EnemyEntity*>(this)){
                EnemyEntity *entity = dynamic_cast<EnemyEntity*>(this);
                entity->changeDirection();
            }
        }
        else if(pos.x > (screenSize.width - halfWidth)){
            pos.x = screenSize.width - halfWidth;
            
            if (dynamic_cast<EnemyEntity*>(this)){
                EnemyEntity *entity = dynamic_cast<EnemyEntity*>(this);
                entity->changeDirection();
            }
        }
        
        if (pos.y < halfHeight){
            pos.y = halfHeight;
            
            if (dynamic_cast<EnemyEntity*>(this))
            {
                EnemyEntity *entity = dynamic_cast<EnemyEntity*>(this);
                entity->changeDirection();
            }
        }
        else if(pos.y > (screenSize.height - halfHeight)){
            pos.y = screenSize.height - halfHeight;
            
            if (dynamic_cast<EnemyEntity*>(this))
            {
                EnemyEntity *entity = dynamic_cast<EnemyEntity*>(this);
                entity->changeDirection();
            }
        }
        if(this->getRotation() == 0) {
            hasCollision = this->checkUpCollision(pos);
        }
        else if (this->getRotation() == 90) {
            hasCollision = this->checkRightCollision(pos);
        }
        else if(this->getRotation() == 180) {
            hasCollision = this->checkDownCollision(pos);
        }
        else if(this->getRotation() == 270) {
            hasCollision = this->checkLeftCollision(pos);
        }
    }

    if (!hasCollision) {
        this->setPosition(pos);
    }
    else if(dynamic_cast<EnemyEntity *>(this)){
        auto entity = dynamic_cast<EnemyEntity *>(this);
        entity->changeDirection();
    }
}