What's wrong with this code?

Monkey Forums/Monkey Beginners/What's wrong with this code?

Nicolas(Posted 2014) [#1]
obj.SetSpeedX(10)

If (obj.xPos >450) Then

obj.SetSpeedX(-10)

How come my obj. stuck in one place. It's like its trying to move but it cant.


Jesse(Posted 2014) [#2]
are you adding speedx to the position of your object?


Nicolas(Posted 2014) [#3]
I'm trying to make the object to move back (bounce)


AdamRedwoods(Posted 2014) [#4]
obj.SetSpeedX(10) 

If (obj.xPos >450) Then obj.SetSpeedX(-10)

1. try setting the if/then on one line. using "Then" with "If" is usually one line. use "If" and "EndIf" if using multiple lines.
2. you should SetSpeedX to "0" unless your function is cumulative "speed=speed+myNewSpeed".


Midimaster(Posted 2014) [#5]
If you always set speed to 10 and only set speed to -10 when the object is over the border, the object will not return, but keep staying at the border!
Try this:

If obj.xPos<0 Then obj.SetSpeedX(10)
If obj.xPos>450 Then obj.SetSpeedX(-10)


This needs a definition of SpeedX when creating the object.
Method New()
    ...
    Self.SpeedX=10

And it works only if there is anywhere a line with...
obj.xPos=obj.xPos+obj.SpeedX


By the way... I would encapsle all this things into the Object-Class

OnRender()
     obj.Draw()
     ....
End
 
Class Object
    Field  SpeedX%=10, xPos%, yPos%

    Method Draw()
        DrawRect xPos,yPos,5,5
        xPos=xPos+SpeedX
        CheckBorders
    End

    Method CheckBorders()
        If xPos<0 Then SpeedX=10
        If xPos>450 Then SpeedX=-10
    End



MikeHart(Posted 2014) [#6]
Nicolas,

by any chance. Are you using fantomEngine in your app?