Page 1 of 1

Bullet code not working.

Posted: Wed Jan 01, 2014 9:22 am
by Creepercats
Hello i tried to make my character shoot a pic that looks like laser here is the code

Code: Select all

bullet_speed = 50


bullet ={}

function bullet.spawn(x,y,dir)
	table.insert(bullet,{width = 50, height = 50, x = x, y = y, dir = dir})
end
function bullet.draw()
	for i,v in ipairs(bullet) do
	love.graphics.newImage("images/Laser.png",v.x,v.y,v.width,v.height)
	end
end


function bullet.update(dt)
	for i,v in ipairs(bullet) do
	if v.dir == "up" then
		v.x = v.x + bullet_speed * dt
	end
	end
end


function bullet.shoot(key)
	if key == "up" then
		bullet.spawn(player.y + player.height, player.y + player.height/2, "up" )
	end
end
The code works fine but when i press the key it does nothing, Got any ideas anyone, btw my main file has bin linked up with this one so that's not the problem Thanks and happy new year



~CreeperCats Dev

Re: Bullet code not working.

Posted: Wed Jan 01, 2014 11:17 am
by MadByte
Hi,

you shouldn't define the image itself inside the love.draw loop. Instead put it to the "bullet_speed" var and then use love.graphics.draw(img, x, y) inside the draw function.

Re: Bullet code not working.

Posted: Wed Jan 01, 2014 11:36 am
by Creepercats
MadByte wrote:Hi,

you shouldn't define the image itself inside the love.draw loop. Instead put it to the "bullet_speed" var and then use love.graphics.draw(img, x, y) inside the draw function.
Thanks for your reply many i get an example i'm not following 100% if you can that would be great thanks :)

Re: Bullet code not working.

Posted: Wed Jan 01, 2014 12:11 pm
by MadByte

Code: Select all



bullet_speed = 50
bullet_img = love.graphics.newImage("images/Laser.png")
bullet ={}

function bullet.spawn(x,y,dir)
   table.insert(bullet,{width = 50, height = 50, x = x, y = y, dir = dir})
end


function bullet.draw()
   for i,v in ipairs(bullet) do
		love.graphics.setColor(255, 255, 255, 255)
		love.graphics.draw(bullet_img, v.x, v.y)
   end
end


function bullet.update(dt)
   for i,v in ipairs(bullet) do
   if v.dir == "up" then
      v.x = v.x + bullet_speed * dt
   end
   end
end


function bullet.shoot(key)
   if key == "up" then
      bullet.spawn(player.y + player.height, player.y + player.height/2, "up" )
   end
end
btw the width and height values does not make much sense as far as I understand your code. If you need them for collision detection with the image use "width = bullet_image:getWidth(), height = bullet_image:getHeight()", this will return the image size.

Re: Bullet code not working.

Posted: Wed Jan 01, 2014 10:22 pm
by micha
To catch key-presses, you need the love.keypressed-callback.