Development Environment: MacOS
Reference Material: Teacher Chen Yun's SDL2 Tutorial
Implementing mouse events in SDL2 is relatively simple; you just need to add a switch
or if
in the event_loop
:
However, to implement drag events, we need to make some significant modifications.
First, we abstract RectShape
using object-oriented thinking, creating a structure and several necessary functions in the header file.
Next, we implement it step by step:
First, creating the rectangle, which is quite simple:
_dragEnabled
determines whether the drag property is enabled, ensuring that the property does not activate when the mouse is not pressed (enabling it directly would lead to automatic pathfinding).
Then, the basic destroy and draw functions:
dest->color
cannot be used directly; it needs to be calculated using right shifts to extract the elements (color RGBA).
The most important part: how to implement the drag event?
Additionally, to restrict the area: only allow dragging within the rectangle's area.
Then, in the main function, draw a small rectangle and configure it: