You can display a line with
love.graphics.line
For the line in the direction the square is going you can do like this:
Code: Select all
local cx, cy = game.x+20, game.y+20 -- square center
love.graphics.line(cx, cy, cx+game.vx*20, cy+game.vy*20)
If you want the segment to end exactly where the square will hit the edge, you can do something like this (assuming that the first point of the segment must be the center of the square)
(I'm trying to keep it simple, say so if you have any problems):
Code: Select all
local cx, cy = game.x+20, game.y+20
local hit_x = (game.vx > 0) and love.graphics.getWidth() or 0
local hit_y = cy + ((hit_x - cx) / game.vx) * game.vy
love.graphics.line(cx, cy, hit_x, hit_y)
If you need precision do not hesitate, I leave you the quick rewrite that I did if you want it. I took the liberty of simplifying it a bit.
Here I replaced your variables mov_x, mov_y by vx, vy which means velocity.
These are values between -1 and 1, and you can multiply them by the speed of the object to get the movement in the right direction with the right speed as well. I also added speed multiplication by 'dt'. Example:
Code: Select all
x = x + vx * 100 * dt -- direction * speed (speed * dt represents the number of pixels traveled in 1 second)
It will be more practical for also calculating the second point of our segment (and also practical for many other types of calculations).
Code: Select all
math.randomseed(os.time()) -- Initialize a seed of randomness with the present time, otherwise the numbers generated by random will always be the same
function love.load()
game = {
x = love.graphics.getWidth() / 2,
y = love.graphics.getHeight() / 2,
vx = math.random() < .5 and -1 or 1, -- Start with random direction
vy = math.random() < .5 and -1 or 1
}
end
function love.update(dt)
game.y = game.y + game.vy * 100 * dt -- (Velocity * Speed * dt) - (100*dt corresponds to 100 pixels per second)
game.x = game.x + game.vx * 100 * dt
if game.x < 0 or game.x + 40 > love.graphics.getWidth() then -- If we touch an edge, we reverse the direction
game.vx = -game.vx
end
if game.y < 0 or game.y + 40 > love.graphics.getHeight() then
game.vy = -game.vy
end
end
function love.draw()
love.graphics.rectangle("line", game.x, game.y, 40, 40)
local cx, cy = game.x+20, game.y+20
local hit_x = (game.vx > 0) and love.graphics.getWidth() or 0
local hit_y = cy + ((hit_x - cx) / game.vx) * game.vy
love.graphics.line(cx, cy, hit_x, hit_y)
love.graphics.print("X:"..game.x.." mov_x:"..game.vx*100)
love.graphics.print("Y:"..game.y.." mov_y:"..game.vy*100, 0, 10)
end