Love - Animation

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

Requirements

You need to have followed the installation process for the Love engine.

You also need to have created a minimal game (ie a new folder, with a 'main.lua' file)

You need to have added this code to 'main.lua':

function love.load()

end

function love.update(dt)

end
 
function love.draw()

end

My code will use this image: Player.png

Required Variables

We need to add the following variables before your 'love.load()':

fps = 10
width = 120
current = 0
frames = 4
duration = 1/fps

The variable fps is the number of frames per second, this will give you some degree of control and also compensate for varying processing power.

Width is the width of a single frame, if your sprite sheet contained multiple rows (normally one per animation) you would also need to use height.

Current will be the current frame, and frames is the total number of frames in this animation.

Duration is calculated from the frames per second, this will be used to ensure we only switch frames after a certain amount of time has passed.

Load in the SpriteSheet

Now in the 'love.load()' you need to add the following:

spritesheet = love.graphics.newImage("player.png")
animation = love.graphics.newQuad(current*width, 0, 120, 120, spritesheet:getDimensions())

spritesheet will be the entire image, and animation is essentially a rectangle to represent the part of the spritesheet for the current frame. '120' is the width and height of each frame.

Switch Frames

Now in the 'love.update()' we need to add the code to calculate how long (time wise) we have left for the current frame. If this is less than zero, we need to increment the current frame. Once we have done this we also need to check the number of frames, if we have gone beyond this we need to set the current frame to zero:

duration = duration - dt
if duration <= 0 then
	duration = 1 / fps
	current = current + 1
	if current == frames then
		current = 0
	end
	animation = love.graphics.newQuad(current*width, 0, 120, 120, spritesheet:getDimensions())
end

We must then update the animation rectangle by setting a animation to a new quad.

Draw the current frame

Finally in the 'love.draw()' we need to add the following line to draw the current frame:

love.graphics.draw(spritesheet, animation, 100, 200, 0, 1, 1)

100 is the x position, 200 is the y position, 0 is the rotation, 1 is the x scale, and the final 1 is the y scale.