Issues with Key Presses and Movement (Platformer)

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
WTFsandwich
Prole
Posts: 1
Joined: Tue Mar 13, 2012 4:30 am

Issues with Key Presses and Movement (Platformer)

Post by WTFsandwich »

So, I intend to eventually make a 2D platformer, but having never programmed a game before, I decided to just make a basic engine first to get the hang of game logic. What I'm attempting to do is make the square (character) move left and right, but I'm having trouble with it. I wasn't sure whether to use love.keypressed or love.keyboard.isDown

I attempted it with the former, and on key press, it crashes.

I've also tried it with the keypress functions inside and outside the love.update, wasn't sure about that either.

Here's my code.

Code: Select all

function love.load()
	love.graphics.setMode(640,480)
	height = love.graphics.getHeight()
	width = love.graphics.getWidth()
	gravity = 9.80665
	xvel = 0
	yvel = 0
	maxyvel = 100
	maxxvel = 100
	ground = 0
	xloc = 0
	yloc = 0
end
	
function love.update(dt)
	if yloc - 16 < height then
		yloc = 16
	end
	
	if xloc < 0 then
		xloc = 0
	end
	
	if xloc + 16 > width then
		xloc = width - 16
	end
	
	xloc = xloc + xvel*dt
	yloc = yloc + yvel*dt
end

function love.keypressed(key)
	if key == "left" then
		while xvel < maxxvel do
			xvel = xvel + 1
		end
	end
end
	
function love.keypressed(key)
	if key == "right" then
		while yvel < maxyvel do
			xvel = xvel + 1
		end
	end
end
	
function love.keyreleased(key)
	if key == "left" then
		while xvel > 0 do
			xvel = xvel - 5
		end
	end
end
	
function love.keyreleased(key)
	if key == "right" then
		while xvel > 0 do
			xvel = xvel - 5
		end
	end
end
	
function love.draw()
	love.graphics.rectangle("line", 320, 464, 16,16)
	love.graphics.print("X LOCATION = " .. xloc, 10, 10)
	love.graphics.print("Y LOCATION = " .. yloc, 10, 30)
	love.graphics.print("X VELOCITY = " .. xvel, 10, 50)
	love.graphics.print("Y VELOCITY = " .. yvel, 10, 70)
end
Any help would be greatly appreciated.
User avatar
bartbes
Sex machine
Posts: 4946
Joined: Fri Aug 29, 2008 10:35 am
Location: The Netherlands
Contact:

Re: Issues with Key Presses and Movement (Platformer)

Post by bartbes »

WTFsandwich wrote:

Code: Select all

--snip
		while xvel > 0 do
			xvel = xvel - 5
		end
--snip
Well, no wonder, you want that to happen once, so turn that into an if instead of a while.
Post Reply

Who is online

Users browsing this forum: Google [Bot], slime and 5 guests