B4J Question Just for fun. Bouncing of a ball with orientation

zed

Well-Known Member
Licensed User
B4J:
Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    
    
    Private Timer1 As Timer
    Private Sprite As B4XView
    Private SpeedX As Float = 5
    Private SpeedY As Float = -5
    Private TraineeList As List
    Private pnlGame As Pane
End Sub

Public Sub Initialize
'    B4XPages.GetManager.LogEvents = True
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
    Sprite.SetBitmap(xui.LoadBitmap(File.DirAssets, "Ballon.png") )
    Sprite.Width = 50
    Sprite.Height = 50

    TraineeList.Initialize

    Timer1.Initialize("Timer1", 30)
    Timer1.Enabled = True
End Sub

Sub Timer1_Tick
    Dim newX As Float = Sprite.Left + SpeedX
    Dim newY As Float = Sprite.Top + SpeedY

    ' Limit checking and bouncing
    If newX <= 0 Or newX + Sprite.Width >= pnlGame.Width Then
        SpeedX = -SpeedX
        ' Small variation to avoid overly predictable rebounds
        SpeedY = SpeedY + Rnd(-2, 2)
    End If
    If newY <= 0 Or newY + Sprite.Height >= pnlGame.Height Then
        SpeedY = -SpeedY
        SpeedX = SpeedX + Rnd(-2, 2)
    End If

    ' Calculating the angle to orient the burning balloon
    Dim angle As Float = ATan2(SpeedY, SpeedX) * 180 / cPI
    ' Turn the ball according to the movement
    Sprite.SetRotationAnimated(30,angle)
    
    Sprite.Left = newX
    Sprite.Top = newY
End Sub
 

Attachments

  • Boucing.gif
    Boucing.gif
    370.6 KB · Views: 94
  • BouncingBall.zip
    47.1 KB · Views: 81
Top