在尝试在Corona SDK中平铺地面时遇到异常。
2012-6-5 22:3:36
收藏:0
阅读:181
评论:1
我正在使用以下代码:
ground1.x = ground1.x - 10
ground2.x = ground2.x - 10
ground3.x = ground3.x - 10
ground4.x = ground4.x - 10
ground5.x = ground5.x - 10
ground6.x = ground6.x - 10
ground7.x = ground7.x - 10
ground8.x = ground8.x - 10
if(ground1.x < ( 0 - 75 ) ) then
ground1:removeSelf()
ground1 = ground2
ground2 = ground3
ground3 = ground4
ground4 = ground5
ground6 = ground7
ground7 = ground8
local num = math.random ( 1, 4 )
ground8 = display.newImage( group, "normalground"..num..".png", ground7.x + ground7.contentWidth/2, display.contentHeight - 52 )
来制作动态地面。我使用了8个块,ground1-ground8。这段代码在我的“enterFrame”中调用了一个animate函数。
我的目标是当“ground1”移动到了左边缘,我会重新分配地砖ground2到ground1,ground3到ground2,依此类推,最后创建一个新的地砖并将其赋给ground8。
我之前做过类似的背景滚动,它一直在正常工作。但当我尝试运行这段代码时,它可以成功地滚动前4个地砖,但一旦它尝试将第5个地砖分配给ground1并通过动画过程,我会收到以下异常:
attempt to perform arithmetic on field 'x' (a nil value)
有任何想法吗?
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
你忘记将
ground6下移至ground5。我不了解 Corona,所以我不知道
removeSelf在内部做了什么,但我猜它销毁了对象和/或删除了它的元表,使得x不再是有效索引。既然您将对象引用从ground5复制到ground4、3、2、1,则最终以这种方式将其销毁,此时ground5.x返回nil,然后您会看到异常。提示:您永远不应该拥有仅因编号不同而不同的变量列表(v1、v2、v3 等)。这就是数组的用途。与其拥有 8 个变量来保存地面图像,不如拥有一个数组,其中包含所有 8 个。然后,您可以使用循环执行操作,例如将它们全部移动 N 个像素。
例如,如果我们将您的 8 张图像放在名为
ground的列表中(例如ground = {ground1,ground2,ground3,ground4,ground5,ground6,ground7,ground8},尽管您可能不会以这种方式初始化它),则可以重写代码:-- 将地面向右平移 10 个像素 for i,tile in pairs(ground) do tile.x = tile.x - 10 end if ground[1].x < (0 - 75) then -- 移除第一个瓷砖 ground[1]:removeSelf() for i=1,#ground-1 do ground[i] = ground[i+1] end -- 在末尾添加一个新的瓷砖 local num = math.random ( 1, 4 ) ground[#ground] = display.newImage( group, "normalground"..num..".png", ground[#ground-1].x + ground[#ground-1].contentWidth/2, display.contentHeight - 52 ) end代码更精简,即使您将 10 个地面砖块移动到 100 个,也无需更改,并避免了您在 OP 中所犯的错误。