# C++ Mouse Input Raylib

## Recommended Posts

Posted (edited)

Hello,

I am trying to get the point counter to increment when the user clicks on a ball using the mouse. I'm using the Raylib library.  I have posted a snippet of my code. I can post if more is needed.

Vector2 mp = GetMousePosition();

RedBall.X_Pos = static_cast <float> (rand() % Width / 2);
RedBall.Y_Pos = static_cast <float> (rand() % Height / 2);

RedBall.X_Vel = 8.0f;
RedBall.Y_Vel = 8.0f;

RedBall.Pos = { RedBall.X_Pos,RedBall.Y_Pos };
RedBall.Vel = { RedBall.X_Vel,RedBall.Y_Vel };

RedBall.Pos.x += RedBall.Vel.x;
RedBall.Pos.y += RedBall.Vel.y;

if ((RedBall.Pos.x >= (GetScreenWidth() - RedBall.Radius)) || (RedBall.Pos.x <= RedBall.Radius)) RedBall.Vel.x *= -1.0f;
if ((RedBall.Pos.y >= (GetScreenHeight() - RedBall.Radius)) || (RedBall.Pos.y <= RedBall.Radius)) RedBall.Vel.y *= -1.0f;

//problem with collision detecting?
{
Player.Current_Game_Score++; //does not increment
}

DrawCircleV(RedBall.Pos, RedBall.Radius, RED);

Edited by LeftyGuitar

##### Share on other sites

So for a 2d game, you can subract the mouse position and the circles position to get a Delta vector. Then check the delta vectors maginude to see if it is less than the circles' radius. If it is, you got collision!

##### Share on other sites

Why do you post ball movement code if you have a question about click positions?

When the "if" doesn't trigger, then either that code is never executed (but then your ball wouldn't move), or the

IsMouseButtonPressed(MOUSE_LEFT_BUTTON) && CheckCollisionPointCircle(RedBall.Pos,mp,RedBall.Radius)

condition fails.

Did you check which yields false at the wrong moment?

My prime suspect would be the CheckCollisionPointCircle, did you try to debug that function? (Step through it while you know what the answer should be, then find the line where it makes the wrong decision.)

##### Share on other sites
Posted (edited)

Ok I seem to make a little bit more progress. Now it sometimes increases the value and other times it doesen't.

EDIT: Ok I figured it out! I needed to put the GetMousePosition inside of the update loop to get the mouse's position in real-time.

Vector2 mp;
Vector2 pos;

RedBall.X_Pos = static_cast <float> (rand() % Width / 2);
RedBall.Y_Pos = static_cast <float> (rand() % Height / 2);

mp = GetMousePosition();
pos = { GetMousePosition().x,GetMousePosition().y };

{
Player.Current_Game_Score++;
}

Edited by LeftyGuitar

## Create an account

Register a new account

• 12
• 19
• 15
• 15
• 10