Corona / Lua 函数范围
我是科罗娜的新手。我不知道如何解决这个问题。
主要是我创建了 2 个本地对象,玩家和敌人。
Player 有一个名为 takeDamage 的函数。
当我尝试从敌人内部调用player.takeDamage时,它看不到该函数。
我认为这是因为 main 拥有这两个对象,并且它们彼此不了解。
我怎样才能让敌人调用该函数,以便它可以对玩家造成伤害?
main.lua 包含:
-- Create player character
local player = require("player");
player = player.new();
-- Create enemy character
local enemy = require("enemy");
enemy = enemy.new();
我认为我可以使播放器全球化,但据我所知,这不是最佳实践。
任何帮助将不胜感激。
I'm new to Corona. I'm not sure how to solve this.
In main I am creating 2 local objects, player and enemy.
Player has a function called takeDamage.
When I try to call player.takeDamage from within enemy, it can't see the function.
I presume it's because main owns both objects and they don't know about each other.
How can I have Enemy call that function so that it can deal damage to Player?
main.lua contains:
-- Create player character
local player = require("player");
player = player.new();
-- Create enemy character
local enemy = require("enemy");
enemy = enemy.new();
I think I could make player global, but from what I know, that would not be a best practice.
Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果可以安全地假设只有一个“玩家”实例,您可以将其设为全局。否则,您将必须按照以下方式执行操作:
然后在敌人代码中使用 self.player 来引用玩家。请注意,这会消耗内存,因为玩家引用将被复制到每个敌人实例。
附带说明一下,我认为将模块和实例(即
player
)称为相同的名称并不好。稍后你会不清楚你指的是模块还是实例。一种安全的方法是将模块称为Player
和Enemy
,代码如下所示:If it is safe to assume that there will be only one "player" instance, you can make it global. Otherwise, you would have to do something along these lines:
And later use
self.player
in the enemy code to reference the player. Note that this will consume memory, because the player reference will be copied to every enemy instance.One side note, I do not consider it good to call a module and an instance the same, i.e.
player
. It will become unclear later if you mean the module, or the instance. A safe way would be to call the modules asPlayer
andEnemy
, and the code will look like this:理想情况下,您不希望玩家直接引用敌人或敌人引用玩家。相反,您可以轮询游戏循环中的每个参与者,并根据结果更新游戏状态。
在真实的游戏中,状态变化将由事件驱动 -触摸事件、绘图事件等。忙循环(
while true do
) 说明了总体思路。您还必须发挥您的想象力来弥补缺失的实施。
游戏建模的方法有很多种。我并不是说这是最好的。然而,它确实展示了一种解耦交互元素的方法。
Ideally, you don't want the player referencing the enemy directly or the enemy referencing the player. Instead, you could poll each participant in a game loop and update the game state based on the result.
In a real game, state change would be driven by events - touch events, drawing events, etc. My busy loop (
while true do
) illustrates the general idea.You'll also have to use your imagination for missing implementation.
There are many ways to model a game. I'm not suggesting this is the best. It does, however, show one way of decoupling interacting elements.