首页 > 解决方案 > 如何在 DragonRuby 游戏工具包中创建按钮

问题描述

DragonRuby Game Toolkit 中似乎没有按钮的概念。如何创建按钮等 UI 组件?

标签: dragonruby-game-toolkit

解决方案


按钮(和任何其他 UI 组件)可以解构为primitives

  1. 按钮有一个点击空间(通常用边框表示)。
  2. 有描述按钮功能的文本。
  3. 响应被点击。

将按钮分解为上述部分会产生以下结果:

def tick args
  # create an entity in state that represents the button
  args.state.click_me_button.border ||= { x: 10, y: 10, w: 100, h: 50 }
  args.state.click_me_button.label  ||= { x: 10, y: 10, text: "click me" }

  # render the button
  args.outputs.borders << args.state.click_me_button.border
  args.outputs.labels << args.state.click_me_button.label

  # determine if the button has been clicked
  if (args.inputs.mouse.click) && 
     (args.inputs.mouse.point.inside_rect? args.state.click_me_button.border)
    args.gtk.notify! "button was clicked"
  end
end

如果你想花哨,可以将上面的按钮代码泛化并放入一个函数中:

# helper method to create a button
def new_button id, x, y, text
  # create a hash ("entity") that has some metadata
  # about what it represents
  entity = {
    id: id,
    rect: { x: x, y: y, w: 100, h: 50 }
  }

  # for that entity, define the primitives 
  # that form it
  entity[:primitives] = [
    { x: x, y: y, w: 100, h: 50 }.border,
    { x: x, y: y, text: text }.label
  ]
    
  entity
end

# helper method for determining if a button was clicked
def button_clicked? args, button
  return false unless args.inputs.mouse.click
  return args.inputs.mouse.point.inside_rect? button[:rect]
end

def tick args
  # use helper method to create a button
  args.state.click_me_button ||= new_button :click_me, 10, 10, "click me"

  # render button generically using `args.outputs.primitives`
  args.outputs.primitives << args.state.click_me_button[:primitives]

  # check if the click occurred using the button_clicked? helper method
  if button_clicked? args, args.state.click_me_button
     args.gtk.notify! "click me button was clicked!"
  end
end

推荐阅读