r/learnprogramming • • 16d ago

Solved Expecting primary expression error

I keep getting the error error: expected primary expression before 'mouse' and error: expected primary expression before 'rect'

Can someone assist me on this because I am lost

CONTEXT

I made a boolean function that detects if a point is colliding with a rectangle and in my main function when button is pressed and mouse is colliding with rectangle than the console needs to output string

bool pointRectCollision(Mouse mouse, RectangleShape rect){
      if(mouse.getPosition().x > int(rect.getPosition().x) && mouse.getPosition.x() < int(rect.getPosition().x + rect.getSize().x) && mouse.getPosition().y > int(rect.getPosition().y) && mouse.getPosition.y() < int(rect.getPosition().y + rect.getSize().y)){
           return true;
      }

      else {
          return false;
       }

}

int main(){

  // GAME LOOP
  if (mouse.isButtonPressed(Button::Left) && pointRectCollision(mouse, pauseBtn)){
        cout << "COLLISION" << endl;
    }


  return 0;
}

UPDATE

I was able to fix the problem. I had to fix the syntax of how I was declaring mouse and also nest my conditional statement for detecting collision.

// function to detect point-rectangle collision
bool pointRectCollision(Vector2i mousePos, RectangleShape &rect){ 
  if(mousePos.x > int(rect.getPosition().x) && mousePos.x < int(rect.getPosition().x + rect.getSize().x) && mousePos.y > int(rect.getPosition().y) && mousePos.y < int(rect.getPosition().y + rect.getSize().y)){
      return true;
}

  else {
    return false;
  }

}

int main(){
  // GAME LOOP

  // MOUSE
  if (Mouse::isButtonPressed(Mouse::Button::Left)){
    if(pointRectCollision(Mouse::getPosition(window), pauseBtn)){
      cout << "collision" << endl;
    }

   }

}
4 Upvotes

8 comments sorted by

2

u/fixermark 16d ago

This would be a good time to practice divide and conquer. Comment out half your code and see if it compiles. If it does, comment out the other half.

Narrow the removed chunks of code until you see where the error is.

This is probably a syntax error because you have a misplaced symbol somewhere, but it's really hard to tell because of that one if statement and its giant middle clause.

1

u/TheEyebal 16d ago

Yeah I will do that.

1

u/aanzeijar 15d ago

Unrelated to your problem but still something that catches the eye of experienced coders:

If you have an expression like this:

if (condition) {
  return true;
} else {
  return false;
}

You should simply return the condition. The extra if may be intuitive to a beginner, but it's pure noise later on.

1

u/TheEyebal 15d ago

So no need for the else statement is what your saying

1

u/lurgi 15d ago

There's no need for the if either.

return condition;

1

u/TheEyebal 15d ago

Ok I will do this thanks

2

u/rupertavery64 16d ago

Is Mouse and RectangleShape declared in a header or before the method call?