在开发游戏时,添加了将窗口尺寸从800 x 600调整为任意大小的功能。这样,我失去了GUI按钮的功能。我怀疑导致该问题的潜在变量是按钮的center_x,center_y,宽度,高度。
当我使用按钮的大小来检查输入时,宽度和高度不太可能会引起问题,按钮的大小会像屏幕一样缩放。我检查的职位却无法扩展。
因此,可能有许多解决此问题的方法,但是我能想到的最简单的方法是:创建按钮实例时,请使用可缩放的变量,而不是不能缩放的变量。
所以不是(center_x,center_y,宽度,高度):
play_button = StartTextButton(60, 570, 100, 40)
类似:
play_button = StartTextButton((SCREEN_WIDTH * ? %), (SCREEN_HEIGHT * ? %), 100, 40)
内在的问题:
1)如何计算按钮的center_x / y以屏幕宽度/高度的百分比表示?
2)如何将像素转换为相对于尺寸的屏幕坐标?
3)是否有更容易忽略的解决方案?
4)无论如何,更简单的方法来决定在何处放置按钮?
感谢任何反馈/帮助。干杯!
检查按钮点击的代码:
def check_mouse_press_for_buttons(x, y, button_list):
""" Given an x, y, see if we need to register any button clicks. """
for button in button_list:
if x > button.center_x + button.width / 2:
continue
if x < button.center_x - button.width / 2:
continue
if y > button.center_y + button.height / 2:
continue
if y < button.center_y - button.height / 2:
continue
button.on_press()
def check_mouse_release_for_buttons(x, y, button_list):
""" If a mouse button has been released, see if we need to process
any release events. """
for button in button_list:
if button.pressed:
button.on_release()
可从Arcade库调整窗口大小的可运行代码示例:
"""
Example showing how handle screen resizing.
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.resizable_window
"""
import arcade
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
START = 0
END = 2000
STEP = 50
class MyGame(arcade.Window):
"""
Main application class.
"""
def __init__(self, width, height):
super().__init__(width, height, title="Resizing Window Example", resizable=True)
arcade.set_background_color(arcade.color.WHITE)
def on_resize(self, width, height):
""" This method is automatically called when the window is resized. """
# Call the parent. Failing to do this will mess up the coordinates, and default to 0,0 at the center and the
# edges being -1 to 1.
super().on_resize(width, height)
print(f"Window resized to: {width}, {height}")
def on_draw(self):
""" Render the screen. """
arcade.start_render()
# Draw the y labels
i = 0
for y in range(START, END, STEP):
arcade.draw_point(0, y, arcade.color.BLUE, 5)
arcade.draw_text(f"{y}", 5, y, arcade.color.BLACK, 12, anchor_x="left", anchor_y="bottom")
i += 1
# Draw the x labels.
i = 1
for x in range(START + STEP, END, STEP):
arcade.draw_point(x, 0, arcade.color.BLUE, 5)
arcade.draw_text(f"{x}", x, 5, arcade.color.BLACK, 12, anchor_x="left", anchor_y="bottom")
i += 1
def main():
MyGame(SCREEN_WIDTH, SCREEN_HEIGHT)
arcade.run()
if __name__ == "__main__":
main()