Today’s little code, sine scroller in Monkey2. In the previous post you can download the code and data files for plain scroller. In this project same data files are used. Let’s take a look at the video:
The scrolling isn’t very smooth in the video, but try the code:
Namespace myapp #Import "<std>" #Import "<mojo>" #Import "gfx/bg.jpg" #Import "fonts/DoctorJekyllNF.ttf" Using std.. Using mojo.. Class MyWindow Extends Window Const SCROLLTEXT:String = " Sine scroller programmed in Monkey2 programming language... One of the traditional sine scrollers seen in Amiga demos... " Field bg:Image Field scrollString:String Field scrollX:Int Field scrollY:Int Field chrStartOffset:Int Field firstChrWidth:Int Field chrEndOffset:Int Field font:Font Field angl:Float Method New( title:String="Simple sine scroller",width:Int=640,height:Int=480,flags:WindowFlags=Null ) Super.New( title,width,height,flags ) bg = Image.Load("asset::bg.jpg") font = Font.Load("asset::DoctorJekyllNF.ttf",80) chrStartOffset = 0 firstChrWidth = font.TextWidth(SCROLLTEXT.Mid(0,1)) scrollX = 0 End Method OnRender( canvas:Canvas ) Override App.RequestRender() canvas.DrawImage(bg,0,0) canvas.Font = font canvas.Color = Color.Orange If scrollX < -firstChrWidth Then chrStartOffset = chrStartOffset + 1 If chrStartOffset > SCROLLTEXT.Length - 1 Then chrStartOffset = 0 firstChrWidth = font.TextWidth(SCROLLTEXT.Mid(chrStartOffset,1)) chrEndOffset = getTextEndOffset() If chrEndOffset > SCROLLTEXT.Length - 1 Then chrEndOffset = 0 scrollX = 0 Endif Local s:String Local position:Int = 0 For Local c:Int = 0 To scrollString.Length - 1 s = scrollString.Mid(c,1) Local angle:Float = ((640.0 / scrollString.Length) / 360.0 * 2) * (Pi / 180) + 8 * (chrStartOffset + c) * (Pi / 180) + angl scrollY = 200 + Sin(angle) * 80 canvas.DrawText(s,scrollX+position,scrollY) position = position + font.TextWidth(scrollString.Mid(c,1)) Next scrollX = scrollX - 2 angl = angl - (Pi / 180) * 4 End Method getTextEndOffset:Int() Local c:Int = chrStartOffset Local textWidth:Int = 0 scrollString = "" ' Find the end offset for a character to build a string ' that's width in pixels is at least 640 + first character's width While textWidth < 640 + firstChrWidth scrollString = scrollString + SCROLLTEXT.Mid(c,1) c = c + 1 If c > SCROLLTEXT.Length - 1 Then c = 0 textWidth = font.TextWidth(scrollString) Wend Return c End End Function Main() New AppInstance New MyWindow App.Run() End
The idea is to build a string (“scrollString”) that’s characters are drawn one by one to the screen in order to achieve the sine wave effect.
Feel free to use this code.