我對 Love2D 和 Lua 感興趣并決定嘗試一下。
因此,為了熟悉 Lua 和 Love2D,我撰寫了一個簡單的示例:
專案結構:
demo
|-ball.lua
|-main.lua
球.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
主程式
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 顏色值確實發生了變化,但球本身沒有改變顏色,任何幫助表示贊賞!
uj5u.com熱心網友回復:
最大的錯誤是顏色定義本身。
顏色范圍從 0(零)到 1。所以改變...
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:changeColor()
self.r = love.math.random()
self.g = love.math.random()
self.b = love.math.random()
print('color: ' .. self.r .. ' ' .. self.g .. ' ' .. self.b)
end
它應該比列印出來...
color: 0.064632309279245 0.45080402957018 0.39887099192605
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/368447.html
下一篇:創建新用戶的物件設計
