Introduction
This is the first part of my atempt to learn Love2d by creating a small, simple platformer.
For this part, i set up a simple program which displays a player and enemies.
The player is then given the ability to move around.
Displaying characters to screen.
The first step to this program is creating and displaying the player character and enemies.
First thing is that i need to draw a character for the player and a character for the enemies.
I opened up GIMP and drew the characters.
For the player, i drew a simple stick man.
For the enemies, i drew a simple goomba looking dude.
To load the images, the Love2d code needed is love.graphics.newImage("path/to/image")
this loads image and allows you to save it to a variable.
To display the image, code needed is love.draw()
and also love.graphics.draw(icon,x,y,r,sx,sy,ox,oy)
love.load()
- callback function which loads things at the very start of the game.
love.draw()
- call back function whcih draws to screen every frame.
love.graphics.draw(icon,x,y)
- function which draws a given image to screen.
- Arguments to function are:
- icon
- image to draw to screen.
- image previously loaded with
love.graphics.newImage
- x
- x postion of image
- y
- y image of image
- icon
combining all of these together into code, it should look a bit like this.
giving us an output which looks like this:
Adding movement
Now that we can display the player onto the screen, we need to move him about.
To accomplish this, we will need to add a few things to our code.
The things needed are a variable for player x, a variable for player y.
We also need the function love.keypressed()
PLAYER_X
andPLAYER_Y
holds the location of player's x and y co-ordinates.love.keypresed()
function which handles keyboard input
We start by creating the global variables for player position.
We next need to change the code in love.draw()
to use these variables.
the last thing needed is to set up the love.keypressed()
function
We used the standard 'wasd' for movement.
We update the global variable for player x and player y when the corresponding key is pressed.
keypress function should look like:
We next need to set boundary for the player. We don't want the player to wander off screen.
To accomplish this, we set up two global variables: HEIGHT
and WIDTH
HEIGHT controls where the bottom of the screen is, and WIDTH controls where the right hand edge of screen is.
All we have to do is add an if statement to each of the movement keys checking if player is out of bounds.
The completed code should look like this:
full code can be found on github
Conclusion
We should now have a simple program which draws characters to the screen and allows the player to move around, but not to move out of bounds.We now know how to draw characters to screen, take in keyboard input, and use this keyboard input to update to change things in game.
Continue to part 2 of this walk through..
No comments:
Post a Comment