How to make rectangle move from side to side

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
erawein
Prole
Posts: 3
Joined: Wed Aug 10, 2016 3:11 pm

How to make rectangle move from side to side

Post 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
User avatar
Plu
Inner party member
Posts: 722
Joined: Fri Mar 15, 2013 9:36 pm

Re: How to make rectangle move from side to side

Post 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
User avatar
Tjakka5
Party member
Posts: 243
Joined: Thu Dec 26, 2013 12:17 pm

Re: How to make rectangle move from side to side

Post 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
erawein
Prole
Posts: 3
Joined: Wed Aug 10, 2016 3:11 pm

Re: How to make rectangle move from side to side

Post 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 :)
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot] and 6 guests