Help with random spawning

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
Zelpal
Prole
Posts: 1
Joined: Wed Jan 24, 2018 2:56 pm

Help with random spawning

Post by Zelpal »

Hey,

I was working on a random tree spawning function, but I've been confronted to a problem.

I first created the function:

Code: Select all

function spawnTree(nb)
  for i = 0, nb-1 do
    Tree = {}
    Tree.x = math.random(0, love.graphics.getWidth())
    Tree.y = math.random(0, love.graphics.getHeight())
    table.insert(Trees, Tree)
    love.graphics.draw(Sprites.Tree1, Tree.x, Tree.y)
  end
end
Then, I called the function in love.draw()

Code: Select all

function love.draw()
   spawnTree(1)
end
And here is the problem:
https://www.youtube.com/watch?v=ahRUYCg ... e=youtu.be

If someone could help, that would be awesome!
Thank you,

Zelpal.
User avatar
Beelz
Party member
Posts: 234
Joined: Thu Sep 24, 2015 1:05 pm
Location: New York, USA
Contact:

Re: Help with random spawning

Post by Beelz »

There are a few things... First, you are calling your create function inside love.draw, which means it will be called every single frame. Also, you're calling the draw function inside the constructor function, that's why it flashes... It only shows for one frame. Here's a small example:

Code: Select all

local trees = {}

function createTree(x, y)
	-- make this local just because... it avoids global conflicts later
	local tree = {
		x = x or math.random(0, love.graphics.getWidth()),
		y = y or math.random(0, love.graphics.getHeight()),
	}
	table.insert(trees, tree)
end

function love.draw()
	for i, tree in ipairs(trees) do
		-- just using a rectangle for now bc I don't have your sprites
		love.graphics.setColor(20,200,20)
		love.graphics.rectangle("fill", tree.x, tree.y, 50, 100)
	end
end

function love.keypressed(k)
	if k == "return" then
		createTree()
	end
end

Code: Select all

if self:hasBeer() then self:drink()
else self:getBeer() end
GitHub -- Website
Post Reply

Who is online

Users browsing this forum: No registered users and 17 guests