Discord
Login
Community
DARK THEME

Is my code correct?

This is code for moving something to a random part of a screen, where you have to click it in a certain amount of time or you lose. Is it correct?

Because after implementing the function under the "draw" function, it showed the sprite to be wildly glitching out!

moveobject = function(spritename)
  ranx = random.next()*336-168
  rany = random.next()*180-90
  ranw = random.nextInt(100)
  ranh = random.nextInt(100)
  screen.drawSprite(spritename,ranx,rany,ranw,ranh)
  
  after 3 seconds do
    if mouse.press then
      if mouse.x < ranx+ranw then
        if mouse.y < rany+ranh then
          print("YAY! you pressed a button")
    else
      print("You didnt press in time")
        end
      end
    end
end
end

This code is not correct and isn't doing what you've written above.

If you are calling this function within the draw function, it will be generating a new value for ranx, rany, ranw, and ranh many times per second. That's why your sprite is moving around so quickly.

You also are using "after" in a very strange way. You'd want to be creating new sprite values EVERY 3 seconds, not testing for input AFTER 3 seconds. Multithreading is hard to reason about. I would just use a counter variable.

Try splitting this up into two functions. One for generating new sprite values, and another for testing input.

// within update...
if counter == 0 then MoveSprite() end
if mouse.press then TestHit() end
counter = (counter+1)%180

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community