Change the text of a label when mouse over it

Started by glurex, Wed 29/03/2023 04:27:45

Previous topic - Next topic

glurex

Hi everyone!

I was trying to do what is on the title. I have a text label (label3) inside a GUI that says "Interact", and I want that when the cursor is over that label the label change its text to "Select" but, when the mouse leaves that label, I want it says "Interact" again.

I thought in using GUIControl  to get the mouse coordinates with GUIControl.GetAtScreenXY(mouse.x, mouse.y). But I have a problem because the text remains fixed in "Select" even when the mouse leaves the label (instead of change to "Interact" again).

That's my faulty code:

Code: ags
GUIControl *guicon = GUIControl.GetAtScreenXY(mouse.x, mouse.y);
Label *lab;

  if (guicon != null) //Mouse is on the label
  {
    lab = guicon.AsLabel;
  }
  if (lab != null)
  {
    if (lab.OwningGUI==gInfo)
    {
      Label3.Text="Select";
      }
    }

Maybe there's a more efficient way to do that. I guess I'm complicating things  :) .

Many thanks!

Khris

You're on the right track but you don't have code that resets the text.
You need a variable that retains its value so you can track whether the mouse has moved over or away from the label since the last frame.
Here's one solution:

Code: ags
// above repeatedly_execute
bool mouseWasOverSelect; // no initial value -> false

  // inside repeatedly_execute
  GUIControl* gc = GUIControl.GetAtScreenXY(mouse.x, mouse.y);
  bool mouseIsOverSelect = gc != null && gc.AsLabel == Label3;

  if (!mouseWasOverSelect && mouseIsOverSelect) Label3.Text = "Interact";
  else if (mouseWasOverSelect && !mouseIsOverSelect) Label3.Text = "Select";

  mouseWasOverSelect = mouseIsOverSelect;

glurex


SMF spam blocked by CleanTalk