Page 1 of 1
How to make rectangle move from side to side
Posted: Wed Aug 10, 2016 3:24 pm
by erawein
It's as simple as it sounds to most of you.
I guess I don't get the logic?
Code: Select all
if x < width then
x = x + 1
elseif x > width then
x = x - 1
obviously the above is wrong, but I hope you know why I'm stuck from it
How can I tell the program to change the direction of the rectangle when it reaches the most outer parts of the screen?
Thanks in advance
Re: How to make rectangle move from side to side
Posted: Wed Aug 10, 2016 4:14 pm
by Plu
You need to store the actual movement direction. As soon as you move one step left, you are no longer at the right-most edge and unless you make the program
remember that it was going in a specific direction, it will move right again (and appear to be stuck)
Code: Select all
if x >= window_width - rectangle_width then
direction = "left"
elseif x <= 0 then
direction = "right"
end
if direction == "left" then
x = x - 1
elseif direction == "right" then
x = x + 1
end
Re: How to make rectangle move from side to side
Posted: Wed Aug 10, 2016 4:56 pm
by Tjakka5
There's a multitude of ways to go about this:
Remembering its direction in a literal way:
Code: Select all
local pos = 0
local dir = "right"
function love.update(dt)
if dir == "right" then
pos = pos + 1
if pos >= love.graphics.getWidth() then
dir = "left"
end
elseif dir == "left" then
pos = pos - 1
if pos <= 0 then
dir = "right"
end
end
end
Remembering its direction in a more abstract, but efficient way:
Code: Select all
local pos = 0
local velocity = 1
function love.update(dt)
pos = pos + velocity
if pos >= love.graphics.getWidth() or pos <= 0 then
velocity = -velocity
end
end
Using a mathematical function with the behaviour you want:
Code: Select all
local pos = 0
local count = 0
function love.update(dt)
count = count + dt
pos = math.sin(count) * (love.graphics.getWidth() / 2) + love.graphics.getWidth() / 2
end
Re: How to make rectangle move from side to side
Posted: Wed Aug 10, 2016 6:00 pm
by erawein
Thank you to both, all the ways mentioned were really informative and got the job done. I'm a beginner so I really can't picture it in an abstract way but now I see