lua moving ball
This commit is contained in:
parent
94eb1fe55e
commit
f129d97f97
1 changed files with 100 additions and 0 deletions
100
lua-moving-ball/main.lua
Normal file
100
lua-moving-ball/main.lua
Normal file
|
@ -0,0 +1,100 @@
|
|||
-- Gist accompanying https://alloca.space/blog/lua-lang.html
|
||||
--
|
||||
-- Build and Run
|
||||
-- -------------
|
||||
--
|
||||
-- 1. Install https://love2d.org on your system
|
||||
--
|
||||
-- 2. Run with:
|
||||
--
|
||||
-- love .
|
||||
|
||||
|
||||
-- Constants
|
||||
|
||||
SCREEN_WIDTH = 640
|
||||
SCREEN_HEIGHT = 480
|
||||
BALL_SPEED = 200
|
||||
BALL_RADIUS = 50
|
||||
|
||||
-- Objects
|
||||
|
||||
local background = {
|
||||
["color"] = {
|
||||
["r"] = 0x08 / 255,
|
||||
["g"] = 0x18 / 255,
|
||||
["b"] = 0x29 / 255,
|
||||
}
|
||||
}
|
||||
|
||||
local ball = {
|
||||
position = {
|
||||
["x"] = SCREEN_WIDTH/3,
|
||||
["y"] = SCREEN_HEIGHT/3,
|
||||
},
|
||||
direction = {
|
||||
["x"] = 1,
|
||||
["y"] = 1,
|
||||
},
|
||||
color = {
|
||||
["r"] = 0xf9 / 255,
|
||||
["g"] = 0x92 / 255,
|
||||
["b"] = 0x26 / 255,
|
||||
},
|
||||
["radius"] = BALL_RADIUS,
|
||||
}
|
||||
|
||||
-- Main
|
||||
|
||||
function love.load()
|
||||
love.window.setMode(SCREEN_WIDTH, SCREEN_HEIGHT, {vsync=true,msaa=4})
|
||||
end
|
||||
|
||||
function love.update()
|
||||
updateBall(ball)
|
||||
end
|
||||
|
||||
function love.draw()
|
||||
love.graphics.clear(background.color.r, background.color.g, background.color.b, 255, true, true)
|
||||
|
||||
love.graphics.setColor(ball.color.r, ball.color.g, ball.color.b)
|
||||
love.graphics.circle("fill", ball.position.x, ball.position.y, ball.radius)
|
||||
end
|
||||
|
||||
-- Update
|
||||
|
||||
function updateBall(ball)
|
||||
applyKeys(ball)
|
||||
swingBall(ball)
|
||||
end
|
||||
|
||||
function applyKeys(ball)
|
||||
if love.keyboard.isDown("d") then ball.direction.x = 1 end
|
||||
if love.keyboard.isDown("a") then ball.direction.x = -1 end
|
||||
if love.keyboard.isDown("s") then ball.direction.y = 1 end
|
||||
if love.keyboard.isDown("w") then ball.direction.y = -1 end
|
||||
end
|
||||
|
||||
function swingBall(ball)
|
||||
local p, d = swing(ball.position.x, ball.direction.x, 0 + ball.radius, SCREEN_WIDTH - ball.radius)
|
||||
ball.position.x = p
|
||||
ball.direction.x = d
|
||||
|
||||
local p, d = swing(ball.position.y, ball.direction.y, 0 + ball.radius, SCREEN_HEIGHT - ball.radius)
|
||||
ball.position.y = p
|
||||
ball.direction.y = d
|
||||
end
|
||||
|
||||
function swing(position, direction, min, max)
|
||||
if (position <= min) then
|
||||
position = min
|
||||
direction = 1
|
||||
elseif (position >= max) then
|
||||
position = max
|
||||
direction = -1
|
||||
end
|
||||
|
||||
local dt = love.timer.getDelta()
|
||||
position = position + (direction * BALL_SPEED * dt)
|
||||
return position, direction
|
||||
end
|
Loading…
Add table
Reference in a new issue