Hello, I’m new to this forum. Hopefully someone will help me with this issue I’ve been having.
I’m creating a game where multiple objects move in random ways inside the screen. I need to avoid this objects going off screen. I’ve been trying to create walls close to the screen edges:
Someone suggested me to use newLine instead of newRect since it’s easier to manage apparently… but it’s not working either way. With this particular version i only get 3 lines that basically divide the screen in half. I don’t really know why.
Does someone know any way to avoid my objects going off screen using some kind of boundaries or even functions?
I’m new at programming so please suggest possible solutions in the easiest way possible.
Thanks for your help! I tried it and it seems to display what i wanted but it gives me this error:
ERROR: Runtime error main.lua:70: bad argument #1 to ‘newRect’ (number expected, got nil) stack traceback: [C]: in function ‘newRect’ main.lua:70: in main chunk
Apparently the error is in this line:
local rect = display.newRect( sceneGroup, 100, 100, 50 ,50 )
It’s not the first time I get this error with “newRect”. Is it a bug?
SceneGroup is a group, in which you should insert your objects, so composer library can control your objects (composer is for scene management).
In a composer scene you would make it like that: local sceneGroup = self.view
But, if you are in main.lua you can just create a normal group: local sceneGroup = display.newGroup()
And when you create your object’s 1st parameter is parent(group): local rect = display.newRect( sceneGroup, 100, 100, 50 ,50 )
@ldurniat’s code looks like a great place to start, but I’d recommend replacing the lines with rectangles (which you may already be doing).
The problem with giving lines a physics body is that the bodies aren’t technically even 1 pixel thick. This means that a fast moving object, or a small enough object, may pass through the lines before the physics bodies wake up and react to the supposed collision.
Having thicker rects will make it more unlikely for objects to pass through other physics bodies unintentionally.