Page 1 of 1

Change image/drawing position to the mouse position every frame

Posted: Sat Nov 11, 2017 2:02 pm
by masterjohn12
I have the following code and I dont know what how to do this

Code: Select all

function love.load()
    image = love.graphics.newImage("ricardo.jpg")
    w, h = love.graphics.getDimensions()
    wi, hi = image:getDimensions()
end

function love.update(dt)
    -- Change image position accordingly to the mouse position
end
-- Draw a coloured rectangle.
function love.draw()
    love.graphics.draw(image, w/2, h/2, 0, 0.5,0.5,wi/2,hi/2)
end

Re: Change image/drawing position to the mouse position every frame

Posted: Sat Nov 11, 2017 4:18 pm
by zorg
Hi and welcome to the forums!

First, you need to get the mouse position, look at the wiki for love.mouse functions.
Then you need two variables to hold the x and y coordinates for your image.
You need to update those variables each frame, as the mouse moves.
Finally, use those variables in love.draw; you only need the first 3 parameters; the image, and the x and y position though.

If you do want to center your image too, then you do require the wi/2 and hi/2 parameters you had before.

Re: Change image/drawing position to the mouse position every frame

Posted: Sat Nov 11, 2017 7:42 pm
by RednibCoding
I've postet something similar on github lately for coding tilemaps:
https://github.com/RednibCoding/Love2D_ ... r/main.lua

Code: Select all

-- in love.update --
-- getting mouse position
	mouseX, mouseY = love.mouse.getPosition()


-- in love.draw --
	-- print the mouseX mouseY position next to the cursor 
	love.graphics.print(mouseX.." | "..mouseY, mouseX, mouseY)
Instead of printing text, just draw your image at mouseX, mouseY

Re: Change image/drawing position to the mouse position every frame

Posted: Sun Nov 12, 2017 2:24 pm
by Tjakka5
Editing your code slightly:

Code: Select all

function love.load()
    image = love.graphics.newImage("ricardo.jpg")
    x, y = 0, 0
    wi, hi = image:getDimensions()
end

function love.update(dt)
    -- Change image position accordingly to the mouse position
    x, y = love.mouse.getPosition()
end
-- Draw a coloured rectangle.
function love.draw()
    love.graphics.draw(image, x, y, 0, 0.5,0.5,wi/2,hi/2)
end