Time for action — acting on object update events

  1. Inside the method we will check if the ball reaches the edges of the game field and change its speed values according to the accelerometer values. The OnObjectUpdate method gives you the object as a parameter.
    Method OnObjectUpdate:Int(obj:ftObject)
    
  2. Perform a SELECT operation on the obj variable:
    Select obj
    
  3. If the object is equal to the object in g.ball, it is our ball:
    Case g.ball
    
  4. Now, check whether the ball reaches the top or bottom edge and whether its y speed value indicates that it is moving towards the corresponding edge:
    If (obj.yPos < obj.GetHeight()/2 And obj.GetSpeedY() < 0) Or (obj.yPos > (g.ch - obj.GetHeight()/2) And obj.GetSpeedY() > 0) Then
    
  5. Reverse the Y speed factor so it will bounce off the edge. Also play the Hit sound effect:
    obj.SetSpeedY(-obj.GetSpeedY())
    g.sndHit.Play()
    Endif
    
  6. Next, check whether the ball reaches the left or right edge and whether its speed x value indicates that it is moving towards that edge:
    If (obj.xPos < obj.GetWidth()/2 And obj.GetSpeedX() < 0) Or (obj.xPos > (g.cw - obj.GetWidth()/2) And obj.GetSpeedX() > 0) Then
    
  7. Reverse the X speed factor, so it will bounce off the edge. Also play the Hit sound effect:
    obj.SetSpeedX(-obj.GetSpeedX())
    g.sndHit.Play()
    Endif
    
  8. Now, read the accelerometer values. By using fantomEngine's GetAccelXY method, you can simulate these by using the up, down, left, and right keys. That is great for testing.
  9. Store the engine's accelerometer values in the local ac array:
    Local ac:Float[] = g.eng.GetAccelXY()
    
  10. Check whether either the x or the y value is different from 0:
    If ac[0]<> 0.0 Or ac[1]<> 0.0 Then
    
  11. Add the current position values to the ac array:
    ac[0] += obj.GetPosX()
    ac[1] += obj.GetPosY()
    
  12. Finally, add a speed value of 1 into the direction, which will be calculated from the object's position to the previous coordinates:
    obj.AddSpeed(1,obj.GetVectorAngle( ac[0], ac[1] ))
    Endif
    End
    Return 0
    End
    

What just happened?

In this method, we are now controlling the ball object. It will bounce off the edges of the screen and we will be able to control it on the device by tilting it, or by the arrow keys on the keyboard if we are on a desktop.

What's the situation? Layer update events

fantomEngine also has callback methods when a layer is updated. It is a good place to check if the game is in a certain state and act on it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.9.115