Page 1 of 1

really basic AI

Posted: Thu Dec 22, 2011 7:22 am
by Ryne
Image

Hi again. Today's task is basic AI. Throughout the game world there will exists small entities, like chickens and rabbits and stuff.

Here is the code I''ll be using to spawn these guys.

Code: Select all

entities = {}

function spawnEntities(type, x, y, w, h, hp, speed, state, dir, anim)

	table.insert(entities, {type = type, x=x, y=y, w=w, h=h, hp=hp, speed=speed, state=state, dir=dir, anim=anim})

end

function updateEntities(dt)
-- code to move them
end

function drawEntities()

	for i=1, #entities do			 
		entities[i].anim:draw(entities[i].x, entities[i].y)
	end

end
which would be used like so

Code: Select all


spawnEntities(chicken, 100, 100, 16, 16, 100, speed, alive, left, anim)

I'd like these guys to move about a small area, for example: if there is a house somewhere, chickens can walk/spawn within 5 tiles of that house. This might also be unnecessary since it might be a better/easier idea to simply give the entities a restriction based on their own x/y. So that wherever the chicken spawns, it can move around as it pleases but within 100px/X amount of tiles from where it spawns.

These chickens have animations for 4 directions. Left/Down/Up/Right, so the animation would need to change based on the direction it's walking in.

This one seems like a difficult task, but I appreciate any help.

Re: really basic AI

Posted: Thu Dec 22, 2011 9:26 am
by Ellohir
I guess there will be someone saying a much better way to do this soon, but what I've thought is just choosing a random direction and then checking if the movement gets you away from the spawn point.

Code: Select all

function math.dist(x1,y1, x2,y2) return ((x2-x1)^2+(y2-y1)^2)^0.5 end

function randomDirection()
    local r = math.random(4)
    if r > 3 then
        animation = "up"
        dx = 5
        dy = 0
    elseif r > 2 then --right
    elseif r > 1 then --down
    else -- r > 0  -  left
    end

    if math.dist(entity.spawnx, entity.spawny, entity.x + dx, entity.y + dy) > entity.walkRadius then
        randomDirection() -- recalculate
    end
end

Re: really basic AI

Posted: Sat Dec 24, 2011 8:37 am
by danlthemanl
I love your pixel art! :awesome: