local EnemySpeed = 50
local PlayerSpeed = 70
-- Distance squared - saves a square root when you can use it directly
local function VecDist2(x1, y1, x2, y2)
return (x2-x1)^2 + (y2-y1)^2
end
-- Distance from a point to another point
local function VecDist(x1, y1, x2, y2)
return math.sqrt(VecDist2(x1, y1, x2, y2))
end
local PlayerX, PlayerY = 400, 300
local EnemyX, EnemyY = 0, 0
function love.update(dt)
if VecDist2(EnemyX, EnemyY, PlayerX, PlayerY) < 100^2 then
-- Make the enemy follow the player
local EnemyToPlayerDist = VecDist(EnemyX, EnemyY, PlayerX, PlayerY)
local NormalizedE2PX = (PlayerX - EnemyX) / EnemyToPlayerDist
local NormalizedE2PY = (PlayerY - EnemyY) / EnemyToPlayerDist
EnemyX = EnemyX + NormalizedE2PX * dt * EnemySpeed
EnemyY = EnemyY + NormalizedE2PY * dt * EnemySpeed
end
local pressed = love.keyboard.isScancodeDown
if pressed("left") then PlayerX = PlayerX - dt * PlayerSpeed end
if pressed("right") then PlayerX = PlayerX + dt * PlayerSpeed end
if pressed("up") then PlayerY = PlayerY - dt * PlayerSpeed end
if pressed("down") then PlayerY = PlayerY + dt * PlayerSpeed end
end
function love.draw()
love.graphics.rectangle("fill", PlayerX - 2, PlayerY - 2, 5, 5)
love.graphics.setColor(1, 0, 0)
love.graphics.rectangle("fill", EnemyX - 2, EnemyY - 2, 5, 5)
love.graphics.setColor(1, 1, 1)
end