viernes, 27 de noviembre de 2015

Parallax Scrolling in Love2d. Part 1: Data Structures and Programming

Hi all!

This is the first post of a series in which I'll explain how we can implement parallax scrolling in Love2d. The code that I'll share is similar to the one I'm using for Breaking Fast, our next game to come.

The implementation builds on the tutorial that you can find here. Actually, I advise you to take a look at this tutorial first, because it covers the fundamental principles behind the implementation. Then, we will perform some extensions, so come back here. 

The implementation starts with the idea of creating a data structure that represents the camera. So now, we will focus on a camera.lua file that implements the camera data and functionalities.

camera.lua
 local camera = {}  
 camera.__index = camera  
 return camera  

What data must a camera have? Well, the first and most important one is the (x,y) coordinates that represent its position. It could also hold data regarding scaling in both directions, and its orientation. If we want the camera to support parallax (and we certainly do), it must also contain a list of layers, where each layer will contain its own objects to be drawn. With this in mind, we can create the camera constructor, as follows:

camera.lua

 local function construct()  
  local self = setmetatable({x = 0, y = 0, scaleX = 1, scaleY = 1, rotation = 0, layers={}}, camera)  
  return self  
 end  
   
 setmetatable(camera, {__call = construct})  

As you can see, we are creating a camera with an empty list of layers. Also, with the setmetatable function, we are instructing that if, from some client code, we use the table camera as a function, the method to which __call points is to be invoked. This means that if we want to create two different cameras from client code, we only need to do the following:

some client code.lua
 local Camera = require "camera"  
 myCamera1 = Camera()  
 myCamera2 = Camera()  

Love2d uses three functions to transform the current coordinate system:

love.graphics.rotate( rotation )
love.graphics.scale( x_scale, y_scale )
love.graphics.translate ( dx, dy )

Let's focus on the last one. According to the documentation: When this function is called with two numbers, dx, and dy, all the following drawing operations take effect as if their x and y coordinates were x+dx and y+dy.

So, assume we have a square in the coordinate (1, 0), as shown on the left part of Figure 1. After performing love.graphics.translate( -1, 0 ), we would have the square in the coordinate (1 + (-1), 0 + 0) = (0, 0), because even when we are actually moving the coordinate system, this is equivalent to moving the square in the opposite direction, as depicted on the right side of Figure 1.


 Figure 1

This is the fundamental mechanism that we can use in order to implement traditional scrolling, where the dx and dy values correspond to the position of the camera with negative sign. The same applies for the scaling and the rotation. We can encapsulate all this in two functions as follows:

camera.lua

 function camera:set()  
  love.graphics.push()  
  love.graphics.rotate(-self.rotation)  
  love.graphics.scale(1 / self.scaleX, 1 / self.scaleY)  
  love.graphics.translate(-self.x, -self.y)  
 end  
   
 function camera:unset()  
  love.graphics.pop()  
 end  

The push() function saves the current transformation on top of a stack, whereas pop() sets the current transformation to the one on top of the stack. The strategy to draw is therefore something similar to this:

camera.lua

 function camera:draw()  
   self:set()
   -- draw stuff  
   self:unset()  
 end  

Obviously, prior to calling self:set(), we could modify properties of the camera, in such a way that each draw call behaves different in terms of scaling, rotation or movement/position.

Let's focus now on the parallax effect. For such effect, we have to turn our attention to the layers. What data must a layer have? First, the layer must be able to draw itself, so it must have a reference to a function that will draw the objects in such a layer. Given that we want that each layer can move at different rates (in order to achieve the parallax effect), each layer must hold a rate or scale value. Finally, it would be interesting that we could decide a relative order among layers, in such a way that we can specify the order in which different layers are drawn. The function that builds a new layer is shown next:

camera.lua

 function camera:newLayer(order, scale, func)  
  local newLayer = {draw = func, scale = scale, order = order}  
  table.insert(self.layers, newLayer)  
  table.sort(self.layers, function(a,b) return a.order < b.order end)  
  return newLayer  
 end  

Note that after inserting the new layer into the table of layers, we order them according to the order value. Now, we can complete the draw function as follows:

camera.lua 

 function camera:draw()  
  local bx, by = self.x, self.y  
  for _, v in ipairs(self.layers) do  
   self.x = bx * v.scale  
   self.y = by * v.scale  
   self:set()  
   v.draw()  
   self:unset()  
  end  
  self.x, self.y = bx, by  
 end  

The draw function iterates over all the layers defined for the camera, it then applies a layer scale to the current position of the camera, which makes each layer to be drawn in a possibly different position, depending on the value of this scale. Finally, the draw function of the layer is called. In order to preserve the original position of the camera, we use the temporary variables bx and by.

Note that given that we are using the product of the layer scale and the current position, stationary objects in layers with scale = 0 will have no movement. Therefore, any static background of the game will belong to a layer with such a scale. A layer with scale = 1 will contain objects that move at the same rate as the camera (but in the opposite direction). If we want to track a character controlled by the player, a good strategy is including it in a layer with scale = 1 and moving it at the same rate as the camera, as we will see later. Anything that moves at a faster or slower rates than the camera will belong to layers with scales greater or lower than 1, respectively. The following post in the series will provide further insight on these statements, but for now, let's see now how some client code can use all of this. Let's assume that we have four layers, that we want to draw in the following order:
  1. Static background layer.
  2. Background layer that moves slowly.
  3. Player layer.
  4. Foreground layer with objects moving much faster than the rate at which the player moves.
The order is important because elements in the layer n+1 will occlude elements in the layer j, 1<=j<n+1 (basically, in all previous layers).

some client code.lua

 myCamera1 = Camera()  
 myCamera1:newLayer(-10, 0, function()    
                love.graphics.setColor(255, 255, 255)   
                love.graphics.draw(staticBackground)  
              end)  
 myCamera1:newLayer(-5, 0.3, function()   
                 love.graphics.setColor(255, 255, 255)  
                 love.graphics.draw(slowBackground)   
                end)  
 myCamera1:newLayer(0, 1.0, function()   
                 love.graphics.setColor(255, 255, 255)  
                 love.graphics.draw(player)   
                end)  
 myCamera1:newLayer(10, 1.5, function()   
                 love.graphics.setColor(255, 255, 255)  
                 love.graphics.draw(foreground)   
                end)  

Of course this is not the end of the story. Client code is responsible for updating and drawing the contents of the camera. Fortunately, this is easy, as it is shown next:

some client code.lua

 function love.draw()  
   myCamera1:draw()  
 end  
   
 function love.update(dt)  
  myCamera1:update(dt, player1.posX)  
 end  

love.draw and love.update(dt) are two framework callbacks provided by Love2d and which developers can override in order to customize their behaviours. The former will essentially call the draw function that we implemented in the camera.lua module, whereas the update function will in turn call an update function in the camera module, which we haven't discussed yet. In this example, we assume that we want the camera to follow the player when it is in the center of the screen. Achieving this requires adding the following lines to the camera.lua file:

camera.lua

 local intendedWidth = 1920  
   
 function camera:setPosition(x, y)  
  self.x = x or self.x  
  self.y = y or self.y  
 end  
   
 function camera:update(dt, posX)  
  if posX > intendedWidth / 2 then  
   self:setPosition(posX - intendedWidth / 2)  
  else  
   self:setPosition(0)  
  end  
 end  

Assuming a resolution (intendedWidth) of 1920 pixels in the horizontal dimension, we want to reposition the camera as soon as the player moves past half of this resolution (center of the screen). From that moment onwards, the camera is repositioned each frame to center the player on the screen. As the player belongs to a layer with scale = 1, the player will remain always in the same position in relation to the camera. This again will be further discussed and mathematically proved in the following post of the series.

And this is for now! I hope you found this tutorial useful. In the next installments of the tutorial, I intend to discuss and provide further insight on three aspects: reasoning about layers scales and their relation with the positions of objects, detecting collisions among objects in different layers and representing objects in different cameras, for example, for local multiplayer games.

See you!

45 comentarios:

  1. Can you please give code files with a usage example

    ResponderEliminar
    Respuestas
    1. Unfortunately, I'm quite busy with my game trying to reach some deadlines. However, copy-pasting the code in this article together with code from this other article: http://nova-fusion.com/2011/04/19/cameras-in-love2d-part-1-the-basics/ should help you have something working pretty fast. Anyway, if you have any concrete question, just let me know and I'll try to answer as fast as I can.

      Eliminar
  2. Use of MS Office is also simple and the user can learn the use of it easily. Online help option is also available in all application of the MS Office which provides an instant guideline.
    office.com/setup
    www.office.com/setup

    ResponderEliminar
  3. MS Office setup is very easy to install, download and redeem. Use of MS Office is also simple and the user can learn the use of it easily. Online help option is also available in all application of the MS Office which provides an instant guideline.

    www.office.com/setup

    ResponderEliminar
  4. office.com/setup - Learn how to download, install, activate, and uninstall Microsoft Office Setup on Mac and Windows. Activate your 25 character alphanumeric product key for Office 365, 2019, 2016, 2013, 2010, or Office 2007 at www.Office.com/setup.

    office.com/setup

    ResponderEliminar
  5. Thank you so much for sharing these amazing tips. I must say you are an incredible writer, I love the way that you describe the things. Please keep sharing.

    For more information visit on office.com/setup | office.com/setup | office.com/setup | Norton.com/setup

    ResponderEliminar
  6. AOI Tech Solutions is a best internet and network security providing company in US, UK, Canada and Australia. Higher customer satisfaction and affordable services. Trained experts with lot of experience. For more details call us - 888-875-4666.

    ResponderEliminar

  7. Tekwire is a best internet and network security providing company in US, UK, Canada and Australia. Higher customer satisfaction and affordable services. Trained experts with lot of experience. For more details call us - 844-479-6777.

    ResponderEliminar

  8. Wire-IT Solutions is a best internet and network security providing company in US, UK, Canada and Australia. Higher customer satisfaction and affordable services. Trained experts with lot of experience.

    ResponderEliminar

  9. Zone Firewall offers comprehensive internet and network security solutions in USA, UK, Canada, and Australia. The qualified experts help with product selection and installation. Product shipping is quick, and pricing is affordable

    ResponderEliminar
  10. Fegon Group LLC is a best internet and network security providing company in US, UK, Canada and Australia. Higher customer satisfaction and affordable services. Trained experts with lot of experience.

    ResponderEliminar
  11. This is really an amazing article. Your article is really good and your article has always good content with a good powerpoint with informative information.

    norton.com/setup

    mcafee.com/activate

    office.com/setup

    ResponderEliminar
  12. Thanks for all the tips mentioned in this article! it’s always good to read things you have heard before and are implementing, but from a different perspective, always pick up some extra bits of information. Visit@
    mcafee.com/activate

    mcafee.com/activate

    norton.com/setup

    ResponderEliminar
  13. I really happy found this website eventually. Really informative and inoperative, Thanks for the post and effort! Please keep sharing more such blog.

    norton.com/setup

    norton.com/setup

    mcafee.com/activate

    kaspersky activation code

    free pogo games

    roadrunner email

    aol mail

    ResponderEliminar
  14. mcafee.com/activate-Contact and connect to live support technician for technical help to fix Mcafee Activate errors from mcafee support.
    www.McAfee.com/Activate | office.com/setup | norton setup | McAfee Activate |www.McAfee.com/Activate | office setup

    ResponderEliminar
  15. I really happy found this website eventually. Really informative and inoperative, Thanks for the post and effort! Please keep sharing more such blog.

    norton.com/setup

    norton.com/setup

    mcafee.com/activate

    kaspersky activation code

    free pogo games

    roadrunner email

    aol mail

    ResponderEliminar
  16. extremely useful to get the simple tips to install McAFee antivirus software using mcafee.com/activate.

    ResponderEliminar
  17. Really great article, Glad to read the article. It is very informative for us. Thanks for posting norton.com/setup

    www.norton.com/setup

    ResponderEliminar
  18. Thank you so much for this Post and all the best for your future. You are really a talented person I have ever seen. I am satisfied with the arrangement of your post i think i must share here www.mcafee.com/activate

    mcafee.com/activate

    ResponderEliminar
  19. Excellent information Providing by your Article, thank you for taking the time to share with us such a nice article post office.com/setup

    www.office.com/setup

    ResponderEliminar

  20. You're a talented blogger. I have joined your bolster and foresee searching for a more noteworthy measure of your amazing post. Also, I have shared your site in my casual networks!


    mcafee.com/Activate
    mcafee.com/Activate
    Office.com/setup
    Office.com/setup
    Norton.com/setup

    ResponderEliminar
  21. Delta Airlines Reservations Much obliged for the pleasant blog. It was exceptionally valuable for me. I'm cheerful I discovered this blog. Much obliged to you for imparting to us, I also consistently discover some new information from your post.

    ResponderEliminar
  22. Delta Airlines Booking Thanks for the nice blog. It was very useful for me. I’m happy I found this blog. Thank you for sharing with us,I too always learn something new from your post.

    ResponderEliminar
  23. Delta Airlines Vacations Packegs Thanks for the nice blog. It was very useful for me. I’m happy I found this blog. Thank you for sharing with us,I too always learn something new from your post.

    ResponderEliminar
  24. Delta Airlines cancellation policy Thanks for the nice blog. It was very useful for me. I’m happy I found this blog. Thank you for sharing with us,I too always learn something new from your post.

    ResponderEliminar
  25. Southwest Airlines Reservations Thanks for the nice blog. It was very useful for me. I’m happy I found this blog. Thank you for sharing with us,I too always learn something new from your post.

    ResponderEliminar
  26. The Hp printer is the finest printer on the market with high quality home and office facilities for everyday use. You need to unbox them if you purchase a new HP

    printer, then set it up with a PC or laptop. By visiting url: 123.hp.com/setup, the user can download and update applications and printer drivers.
    [url=https://www123hpsetup.com/]123.hp.com/setup[/url]
    123.hp.com/setup

    ResponderEliminar
  27. Office.com/setup - Microsoft Office has an excellent collection of applications that have been designed to do many tasks with its different and well-organized

    versions. These versions include Office 2019, Office 365, Office 2016, Office 2013, Office 2010, Office 2007, Office Home & Student and a lot more that can be accessed

    at www.office.com/setup.
    officecom/setup

    ResponderEliminar
  28. McAfee is still among numerous ideal/ideally solidness instruments for pretty much any of your device. This isn’t just an ordinary device that expels infections that

    are little and records bugs. Notwithstanding, this truly is only one all out full soundness supply for the Apparatus. Visit for more info: mcafee.com/activate

    https://mcafeecomactivateuk.000webhostapp.com/

    mcafee.com/activate

    ResponderEliminar
  29. Through www.amazon.com/mytv - how you can connect your mobile phone to Amazon Prime. Through amazon.com/mytv, you can watch your favorite TV shows, series movies. You can watch prime videos anywhere on your device. Users need to create an Amazon account if they don’t have an Amazon account and enter the Amazon my TV activation code to watch Amazon prime videos on your device.

    www.amazon.com/mytv
    amazon.com/mytv

    ResponderEliminar
  30. Through www.amazon.com/mytv - how you can connect your mobile phone to Amazon Prime. Through amazon.com/mytv, you can watch your favorite TV shows, series movies. You can watch prime videos anywhere on your device. Users need to create an Amazon account if they don’t have an Amazon account and enter the Amazon my TV activation code to watch Amazon prime videos on your device.

    www.amazon.com/mytv
    amazon.com/mytv

    ResponderEliminar
  31. www.fubo.tv/connect - You can activate and watch fuboTV on any device on which you want to watch episodes. There are two ways to activate fuboTV by using email and password and fubo activation code using fubo.tv/connect.



    www.fubo.tv/connect

    ResponderEliminar
  32. www.fubo.tv/connect - You can activate and watch fuboTV on any device on which you want to watch episodes. There are two ways to activate fuboTV by using email and password and fubo activation code using fubo.tv/connect.



    fubo.tv/connect

    ResponderEliminar
  33. Hulu.com/activate - To activate Hulu on new gadgets or computers you need to login to your Hulu account at www.hulu.com/activate and enter the activation code Hulu. On the off chance that you do not have to face any issues in Hulu records or hulu activation code volume, you can contact the retention group Hulu for complete direction.

    www.hulu.com/activate
    hulu activation code

    ResponderEliminar

  34. Amazon.com/Mytv Without a doubt, you heard it right. You can watch amazon prime video on a gaming console as well. You just unpacked another Amazon device and are eager to investigate how would you begin? Figure out how to connect your devices to Prime so you can undoubtedly watch and tune in to selective Prime video content from anyplace. amazon.com/mytv Enter code You simply need to create amazon account and activate it by utilizing amazon my tv activation code. Easily Activate Amazon by visiting our website

    amazon com mytv
    amazon.com/mytv Enter code

    ResponderEliminar

  35. On the off chance that you're seeing Amazon Prime on your TV, you essentially need to open the application and get your extraordinary Amazon Activation code. It will be given to you when you endeavor to activate an alternate device for review. For instance, getting a Prime Trial notwithstanding contraption Activation code. At the point when you get the Amazon Activation code, enter it at amazon.com/mytv to complete the activation process.

    ResponderEliminar
  36. Amazon.com/mytv Enter Code You just unpacked another Amazon device and are eager to investigate — how would you begin? Figure out how to connect your devices to Prime so you can undoubtedly watch and tune in to selective Prime video content from anyplace. You simply need to create amazon account and activate it by utilizing amazon my tv activation code. Go to amazon.com/mytv or amazon prime video on PC

    Amazon.com/mytv Enter Code
    Amazon.com/mytv





    ResponderEliminar
  37. Hey Everyone,Are you getting errors when you try to activate your Microsoft office activation subscription? Then read on to get step by step guide to solve Microsoft office activation errors. Install, and activate your Office setup on your computer and other devices.
    office.com/setup
    www.office.com/setup
    setup.office.com
    microsoft365.com/setup
    office.com/renew
    office365.com/setup
    office.com/setup home and student 2019
    office.com/setup home and business 2019
    office setup
    office 2019

    ResponderEliminar
  38. We're working to fix the issues that may come up when using Office,We are here 24/7 to get instant help & support.
    office.com/setup
    microsoft365.com/setup
    office setup
    office.com/renew

    ResponderEliminar


  39. You can get the steps for getting the prime video activation code listed below!You can get the complete guide for getting primevideo.com/mytv code in the guide given below. To get the activation code you should ensure that you have a computer connected to the internet. The device through which you wish to use Amazon Prime Video should also be connected to the internet.


    ResponderEliminar
  40. instagram
    instagram login
    http://eshbrooklyn.com
    instagram video download
    instagram reels download
    instagram download
    instagram reels video download
    instagram story download
    instagram bio for girls
    instagram app
    instagram apk
    instagram account delete
    instagram autofree.in
    instagram account
    instagram appeal form
    instagram account delete permanently
    instagram apk download latest version
    instagram bio
    instagram bio for boys
    instagram blue tick
    instagram background
    instagram bio for girls attitude
    instagram bio for boys in hindi
    instagram blue tick copy
    instagram captions
    instagram captions for boys
    instagram captions for girls
    instagram customer care number
    instagram create new account
    instagram creator studio
    instagram customer care number india
    instagram contact number india
    instagram dp
    instagram download video
    instagram delete account
    instagram download for pc
    instagram download apk
    instagram delete
    instagram dp for girls
    instagram engagement rate
    instagram emoji
    instagram earnings
    instagram email id
    instagram engagement rate calculator
    instagram editing
    instagram emoji logo
    instagram email
    instagram followers
    instagram followers increase
    instagram fonts
    instagram followers hack
    instagram free followers
    instagram font style
    instagram for pc
    instagram forgot password
    instagram girls dp
    instagram girls name
    instagram girls bio
    instagram girls
    instagram group link
    instagram girl pic
    instagram gb
    instagram girls caption

    ResponderEliminar