【发布时间】:2022-01-05 11:23:55
【问题描述】:
我对 Love2D 和 Lua 很感兴趣,并决定尝试一下。
所以为了熟悉 Lua 和 Love2D,我编写了一个简单的示例:
项目结构:
demo
|-ball.lua
|-main.lua
ball.lua
Ball = {
x = 0,
y = 0,
xSpeed = 0,
ySpeed = 0,
ballRadius = 0,
r = 0,
g = 0,
b = 0
}
function Ball:new(x, y, xSpeed, ySpeed, ballRadius, r, g, b)
t = {
x = x,
y = y,
xSpeed = xSpeed,
ySpeed = ySpeed,
ballRadius = ballRadius,
r = r,
g = g,
b = b
}
setmetatable(t, self)
self.__index = self
return t
end
function Ball:move()
self.x = self.x + self.xSpeed
self.y = self.y + self.ySpeed
end
function Ball:changeColor()
self.r = love.math.random(0, 255)
self.g = love.math.random(0, 255)
self.b = love.math.random(0, 255)
print('color: ' .. self.r .. ' ' .. self.g .. ' ' .. self.b)
end
function Ball:checkEdges()
if self.x + self.ballRadius > love.graphics.getWidth() or self.x - self.ballRadius < 0 then
self.xSpeed = self.xSpeed * -1
Ball:changeColor()
end
if self.y + self.ballRadius> love.graphics.getHeight() or self.y - self.ballRadius < 0 then
self.ySpeed = self.ySpeed * -1
Ball:changeColor()
end
end
function Ball:show()
love.graphics.setColor(self.r, self.g, self.b)
love.graphics.ellipse('fill', self.x, self.y, self.ballRadius)
end
main.lua
require "ball"
local ball = nil
local x, y
function love.load()
x = love.graphics.getWidth() / 2
y = love.graphics.getHeight() / 2
ball = Ball:new(x, y, 2, 3.5, 20, 255, 255, 255)
end
function love.update(dt)
Ball.move(ball)
Ball.checkEdges(ball)
end
function love.keypressed(key)
if key == 'escape' then
love.event.quit()
end
end
function love.draw()
love.graphics.setBackgroundColor(0, 0, 0)
Ball.show(ball)
end
所以基本上它只是一个在碰到边缘时弹跳的球。
除了function Ball:changeColor(),一切似乎都很好
我希望球每次碰到边缘时都会改变颜色,但这不起作用。function changeColor() 有问题吗?
这是演示的快照:
函数确实触发了,rgb 颜色值确实改变了,但球本身没有改变颜色,感谢任何帮助!
【问题讨论】:
-
请不要使用love2d :-(,改用solar2d 甚至更好的gideros,你会有很多好东西!不过这是我个人的看法
-
在
Ball:checkEdges内调用函数为self:changeColor()而不是Ball:changeColor() -
@EgorSkriptunoff 那又是一个错误,在改变这个和 changeColor 函数后让它工作了,谢谢!