Click to Move Question [SOLVED]
Posted: Sun Apr 14, 2019 2:41 pm
Hello I want to do this: Player moves towards there and stops when I click somewhere. How can i achieve this? Please note that i am a bit newbie. Thanks in advance!
Code: Select all
function love.load()
circle = {}
mouse = {}
circle.speed = 300
-- just some initial values here
mouse.x, mouse.y = love.mouse.getPosition()
circle.x, circle.y = mouse.x, mouse.y
end
function love.mousepressed(x, y, button)
if button == 1 then
mouse.x, mouse.y = x, y
end
end
function love.update(dt)
if circle.x < mouse.x then
circle.x = circle.x + (circle.speed * 2.5 * dt)
end
if circle.x > mouse.x then
circle.x = circle.x - (circle.speed * 2.5 * dt)
end
if circle.y < mouse.y then
circle.y = circle.y + (circle.speed * 2.5 * dt)
end
if circle.y > mouse.y then
circle.y = circle.y - (circle.speed * 2.5 * dt)
end
end
function love.draw()
love.graphics.setColor(1, 0, 0)
love.graphics.circle("fill", circle.x, circle.y, 50)
end
Code: Select all
-- Returns the distance between two points.
function math.dist(x1,y1, x2,y2) return ((x2-x1)^2+(y2-y1)^2)^0.5 end
-- Returns the angle between two points. Radians!
function math.angle(x1,y1, x2,y2) return math.atan2(y2-y1, x2-x1) end
function love.update(dt)
-- get distance to destination
local distance = math.dist ( circle.x, circle.y, mouse.x, mouse.y )
-- calculate how much we would move this frame
local stepSize = circle.speed * 2.5 * dt
if distance > stepSize then -- if we're further away than stepSize, move towards the mouse's location in a straight line
-- get angle between destination and current location, in radians, and move circle
local angle = math.angle ( circle.x, circle.y, mouse.x, mouse.y )
circle.x = circle.x + math.cos ( angle ) * stepSize
circle.y = circle.y + math.sin ( angle ) * stepSize
else -- if we're not where mouse is, but closer than stepSize, set circle onto mouse position
circle.x, circle.y = mouse.x, mouse.y
end
end
Code: Select all
if distance > stepSize then -- if we're further away than stepSize, move towards the mouse's location in a straight line
circle.x = circle.x + (mouse.x - circle.x) / distance * stepSize
circle.y = circle.y + (mouse.y - circle.y) / distance * stepSize
else
...