While a moving spaceship is cool, what’s even cooler? A spaceship that shoots!
So, you’ve got your spaceship moving left and right on your screen using Codea Lua. That’s great! But let’s be honest, what’s a spaceship without some serious firepower? In this tutorial, we’ll add the ability to shoot bullets from our spaceship.
Step 1: Add the Bullet Sprite
First, let’s declare a table to keep track of our bullets. Add this line at the beginning of your code.
bullets = {}
Step 2: Modify the Spaceship Position
Move your spaceship lower on the screen to make room for the bullets. Update your setup() function as follows:
function setup()
viewer.mode = FULLSCREEN
shipX = WIDTH/2
shipY = HEIGHT/4
end
Step 3: Draw the Bullets
Add this loop inside your draw() function to draw and move the bullets:
for i, bullet in ipairs(bullets) do
ellipse(bullet.x, bullet.y, 10)
bullet.y = bullet.y + 5
if bullet.y > HEIGHT then
table.remove(bullets, i)
end
end
Step 4: Shoot Bullets with Touch
Finally, let’s modify the touched(touch) function to shoot bullets when we tap the screen:
function touched(touch)
if touch.state == BEGAN then
table.insert(bullets, {x = shipX, y = shipY})
end
if touch.x < shipX then
shipX = shipX – 5
elseif touch.x > shipX then
shipX = shipX + 5
end
Complete Code Listing
Here’s your complete updated code:
bullets = {}
function setup()
viewer.mode = FULLSCREEN
shipX = WIDTH/2
shipY = HEIGHT/4
end
function draw()
background(40, 40, 50)
sprite(asset.builtin.Space_Art.Red_Ship, shipX, shipY)
for i, bullet in ipairs(bullets) do
ellipse(bullet.x, bullet.y, 10)
bullet.y = bullet.y + 5
if bullet.y > HEIGHT then
table.remove(bullets, i)
end
end
end
function touched(touch) if touch.state == BEGAN then
table.insert(bullets, {x = shipX, y = shipY})
end
if touch.x < shipX then
shipX = shipX – 5
elseif touch.x > shipX then
shipX = shipX + 5
end
end
And there you have it! Your spaceship not only moves but also shoots bullets upwards. Imagine the possibilities now—dodging asteroids, shooting down alien invaders—you’re limited only by your creativity!
I hope this tutorial helps you take your Codea Lua game to the next level. Happy coding!
Did you like this post? Tell us
Leave a comment
Log in with your itch.io account to leave a comment.