Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Problem with colliding items with scene



  • Hi i am creted enemy in my game and i want when my enemy hit the end of scene to go back in different angle .I Have a problem with implementation
    0_1557159745351_RandomAngleForEnemy.png
    I want something like this

    this is my move method

    void Enemy::move()
    {

    /*Check collision with other enemies .This works fine*/
    QList <QGraphicsItem *>colliding_items = collidingItems();
    for(int i=0,n=colliding_items.size();i<n;i++)
    {
        if(typeid (*(colliding_items[i]))==typeid (Enemy))
    {
               //remove them both
            scene()->removeItem(colliding_items[i]);
            scene()->removeItem(this);
    
            //delete from heap
            delete colliding_items[i];
            delete this;
            return;
    }
    }
    
    
    
    
    
    
    
    
    //moving enemy down
     setPos(x(),y()+5);
    
    
       
    
    
    
    
    
       if(scene()->collidingItems(this).isEmpty())
           {
               //no collision
              qDebug() << "Still no collision";
           }
           else
           {
               //collision!!!!
    
    
               //Set the position
               DoCollision();
           }
    

    }

    now goes do collision method

    //Get a new position
    
     //Change the angle with a little randomness
     if(((qrand() %1)))
     {
         setRotation(rotation() + (180 + (qrand() % 10)));
     }
     else
     {
         setRotation(rotation() + (180 + (qrand() % -10)));
     }
    
     //see if the new position is in bounds
     QPointF newpoint = mapToParent(-(boundingRect().width()), -(boundingRect().width() + 2));
    
    
    
     if(!scene()->sceneRect().contains((newpoint)))
     {
         //move it back in bounds
         newpoint = mapToParent(0,0);
     }
     else
     {
         //set the new position
         qDebug() << "Collision";
         setPos(newpoint);
    
    
     }
    

    this is my constructor

    Enemy::Enemy():QObject(),QGraphicsPixMapItem()
    {

    int random_number = (rand() % 700)+80;

    setPos(random_number,0);
    
    // drew the rect
    setPixmap(QPixmap(":/res/RSC/enemy.png"));
    setRotation(180);
    
    // connect
    QTimer * timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(move()));
    
    timer->start(50)
    

    }


Log in to reply