[Math] LoopValue and LimitValue

About Monkey 2 Forums Monkey 2 Code Library [Math] LoopValue and LimitValue

This topic contains 0 replies, has 1 voice, and was last updated by  cocon 1 year, 10 months ago.

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #8789

    cocon
    Participant

    Two useful functions.

     

    LoopValue: Will allow you to loop a value within a range.
    LimitValue: Will allow you to limit a value within a range.

    The original value. @param startRange The start of the range. @param endRange The end of the range. @return value The original value looped into the range. #end Function LoopValue<T>:T(value:T, startRange:T, endRange:T) value = value Mod endRange If (value < startRange) value += endRange Return value End #rem monkeydoc Limits a value within a specified range. @param value The original value. @param startRange The start of the range. @param endRange The end of the range. @return value The original value looped into the range. #end Function LimitValue<T>:T(value:T, startRange:T, endRange:T) If (value < startRange) value = startRange Elseif (value > endRange) value = endRange End Return value End '________________________________________________________________ Class MovableObject Field Position:Vec2f Field Color:Color Field Size:Float Method New() Position = New Vec2f() Self.Color = Color.White Size = 50 End Method SetPosition(x:Float, y:Float) Position.X = x Position.Y = y End Method UpdateFalling(speed:Float) Position.Y += speed End Method UpdateSliding(speed:Float) Position.X += speed End Method Draw(canvas:Canvas) canvas.Color = Self.Color canvas.DrawRect(Position.X - (Size/2), Position.Y - (Size/2), Size, Size) End End Class MyWindow Extends Window Field ob1:MovableObject Field ob2:MovableObject Field ob2Speed:Float = 10 Method New() ob1 = New MovableObject ob1.SetPosition(Width / 2, Height / 2) ob1.Position.X -= ob1.Size ob1.Color = Color.Blue ob2 = New MovableObject ob2.SetPosition(Width / 2, Height / 2) ob2.Position.Y += ob2.Size ob2.Color = Color.Yellow End Method OnRender(canvas:Canvas) Override App.RequestRender() ' Update object 1 with endless falling ob1.UpdateFalling(5) ob1.Position.Y = LoopValue(ob1.Position.Y, Cast<Float>(0), Cast<Float>(Height)) ob1.Draw(canvas) ' Update object 2 by making it bounce ob2.UpdateSliding(ob2Speed) ' -- compare the original position to a limited one, if result is greater than 0 means a collision. ' -- this is an alternative way for collision detection for avoiding writing the "if-then-else" statement. If ob2.Position.X - LimitValue(ob2.Position.X, Cast<Float>(0), Cast<Float>(Width)) <> 0.0 Then ob2Speed *= -1 ' ... using this statement instead would make the object stop once it reaches the limits. 'ob2.Position.X = LimitValue(ob2.Position.X, Cast<Float>(0), Cast<Float>(Width)) ob2.Draw(canvas) End End Function Main() New AppInstance New MyWindow App.Run() End[/crayon]
Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.