You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua新手如何在Codea引擎中正确创建可用按钮?

Codea 引擎 Lua 自定义按钮实现方案

以下实现完全不依赖 fn 相关标签/API,可直接在你的项目中运行使用:

核心实现逻辑

  • 按钮的本质是「可交互区域+样式绘制+点击回调」,无需依赖官方封装组件即可手动实现
  • 调用 Codea 原生的 draw() 生命周期函数绘制按钮样式
  • 调用 Codea 原生的 touched(touch) 生命周期函数监听触摸事件,判断触摸是否落在按钮区域内触发对应逻辑

可运行示例代码

-- 定义按钮配置表
local testButton = {
    -- 位置尺寸配置
    centerX = WIDTH / 2,
    centerY = HEIGHT / 2,
    width = 220,
    height = 75,
    -- 样式配置
    normalBgColor = color(30, 144, 255),
    pressedBgColor = color(70, 170, 255),
    textColor = color(255, 255, 255),
    buttonText = "确认",
    -- 状态标记
    isPressed = false,
    -- 点击回调
    onClick = function()
        print("按钮触发成功")
        -- 此处替换为你的按钮点击逻辑
    end
}

-- 每帧执行的绘制函数
function draw()
    background(50, 50, 60)
    
    -- 绘制按钮背景
    if testButton.isPressed then
        fill(testButton.pressedBgColor)
    else
        fill(testButton.normalBgColor)
    end
    -- 绘制圆角矩形按钮,最后一个参数为圆角半径
    roundedRect(
        testButton.centerX - testButton.width/2,
        testButton.centerY - testButton.height/2,
        testButton.width,
        testButton.height,
        12
    )
    
    -- 绘制按钮文字
    fill(testButton.textColor)
    fontSize(26)
    textMode(CENTER)
    text(testButton.buttonText, testButton.centerX, testButton.centerY)
end

-- 触摸事件监听函数
function touched(touch)
    -- 计算触摸点是否在按钮区域内
    local touchInArea = 
        touch.x >= testButton.centerX - testButton.width/2 and
        touch.x <= testButton.centerX + testButton.width/2 and
        touch.y >= testButton.centerY - testButton.height/2 and
        touch.y <= testButton.centerY + testButton.height/2
    
    if touch.state == BEGAN and touchInArea then
        testButton.isPressed = true
    elseif touch.state == ENDED then
        if testButton.isPressed and touchInArea then
            -- 触摸在按钮范围内抬起,触发点击回调
            testButton.onClick()
        end
        testButton.isPressed = false
    end
end

扩展使用说明

  • 需要多个按钮时,将按钮配置封装为类,实例化后存入数组,在draw()和touched()中遍历执行对应逻辑即可
  • 需要异形按钮时,仅修改touched()函数中的区域判断规则即可,其余逻辑无需改动
  • 所有逻辑均使用Codea原生API实现,不涉及任何fn相关的调用,适配你当前的环境

内容的提问来源于stack exchange,提问作者LeafTea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 14:06:04