### Advanced Game State with Callbacks Example Source: https://hump.readthedocs.io/en/latest/gamestate Demonstrates a more detailed use of gamestate callbacks, including init, enter, update, draw, keyreleased, and mousereleased. This example shows how to manage UI elements like buttons within a game state. ```lua menu = {} function menu:init() self.background = love.graphics.newImage('bg.jpg') Buttons.initialize() end function menu:enter(previous) -- runs every time the state is entered Buttons.setActive(Buttons.start) end function menu:update(dt) -- runs every frame Buttons.update(dt) end function menu:draw() love.graphics.draw(self.background, 0, 0) Buttons.draw() end function menu:keyreleased(key) if key == 'up' then Buttons.selectPrevious() elseif key == 'down' then Buttons.selectNext() elseif Buttons.active:onClick() end end function menu:mousereleased(x,y, mouse_btn) local button = Buttons.hovered(x,y) if button then Button.select(button) if mouse_btn == 'l' then button:onClick() end end end ``` -------------------------------- ### Basic Tweening Example in Hump Source: https://hump.readthedocs.io/en/latest/timer Demonstrates initiating two tweens for player object attributes 'x' and 'y' with different durations. The tweening behavior is controlled by underlying interpolation methods. ```lua -- now: player.x = 0, player.y = 0 Timer.tween(2, player, {x = 2}) Timer.tween(4, player, {y = 8}) ``` -------------------------------- ### Player Update Logic Using hump.vector-light Functions Source: https://hump.readthedocs.io/en/latest/vector-light An example function demonstrating player movement updates using functions from the hump.vector-light module. It handles keyboard input, vector normalization, addition, scaling, and velocity clamping. ```lua function player:update(dt) local dx,dy = 0,0 if love.keyboard.isDown('left') then dx = -1 elseif love.keyboard.isDown('right') then dx = 1 end if love.keyboard.isDown('up') then dy = -1 elseif love.keyboard.isDown('down') then dy = 1 end dx,dy = vector.normalize(dx, dy) player.velx, player.vely = vector.add(player.velx, player.vely, vector.mul(dy, dx, dy)) if vector.len(player.velx, player.vely) > player.max_velocity then player.velx, player.vely = vector.mul(player.max_velocity, vector.normalize(player.velx, player.vely) end player.x = player.x + dt * player.velx player.y = player.y + dt * player.velx end ``` -------------------------------- ### Scheduling and Updating Timers with hump.timer (Lua) Source: https://hump.readthedocs.io/en/latest/timer This example shows how to schedule a function to run after a delay using Timer.after and how to update the timer system within the love.update loop. It's crucial for the timer system to be updated regularly to trigger scheduled functions. ```lua function love.keypressed(key) if key == ' ' then Timer.after(1, function() print("Hello, world!") end) end end function love.update(dt) Timer.update(dt) end ``` -------------------------------- ### Vector Arithmetic Examples with hump.vector Source: https://hump.readthedocs.io/en/latest/vector Illustrates common vector arithmetic operations provided by hump.vector, including addition, subtraction, dot product, scalar multiplication, and division. These operations are implemented using Lua's metamethods. ```lua -- acceleration, player.velocity and player.position are vectors acceleration = vector(0,-9) player.velocity = player.velocity + acceleration * dt player.position = player.position + player.velocity * dt ``` -------------------------------- ### Basic Game State Management Example Source: https://hump.readthedocs.io/en/latest/gamestate Illustrates a typical game structure using hump.gamestate, with a menu state and a game state. It shows how to switch between states and define basic callbacks for drawing and input handling. ```lua local menu = {} local game = {} function menu:draw() love.graphics.print("Press Enter to continue", 10, 10) end function menu:keyreleased(key, code) if key == 'return' then Gamestate.switch(game) end end function game:enter() Entities.clear() -- setup entities here end function game:update(dt) Entities.update(dt) end function game:draw() Entities.draw() end function love.load() Gamestate.registerEvents() Gamestate.switch(menu) end ``` -------------------------------- ### Mouse Position and Locking Utilities Source: https://hump.readthedocs.io/en/latest/camera Offers utilities for getting the mouse position relative to the camera and for locking the camera's position to specific axes or a window area. Locking functions can incorporate smoothing. ```lua camera:mousePosition() camera:lockX(x, smoother, ...) camera:lockY(y, smoother, ...) camera:lockPosition(x, y, smoother, ...) camera:lockWindow(x, y, x_min, x_max, y_min, y_max, smoother, ...) ``` -------------------------------- ### Attach Camera Transformations Source: https://hump.readthedocs.io/en/latest/camera Starts applying camera transformations (move, scale, rotate) to subsequent drawing operations. This function must be paired with camera:detach(). ```lua function love.draw() camera:attach() draw_world() camera:detach() draw_hud() end ``` -------------------------------- ### Caveats of Custom __index Metamethods in Classes Source: https://hump.readthedocs.io/en/latest/class Warns against defining a custom `__index` metamethod directly on a class, as it can interfere with the class mechanism and prevent subclasses from inheriting correctly. The example shows how to use `rawget` to properly implement a custom `__index` without breaking subclass functionality. ```lua Class = require 'hump.class' A = Class{} function A:foo() print('bar') end function A:__index(key) print(key) return rawget(A, key) end instance = A() instance:foo() -- prints foo bar B = Class{__includes = A} instance = B() instance:foo() -- prints only foo ``` -------------------------------- ### Get Mouse Position in World Coordinates Source: https://hump.readthedocs.io/en/latest/camera A convenience function to get the current mouse position directly in world coordinates. It internally calls `camera:worldCoords()` with the current mouse position. This is useful for direct interaction with game world elements based on mouse input. ```lua x,y = camera:mousePosition() selectedUnit:plotPath(x,y) ``` -------------------------------- ### Get Camera Position Source: https://hump.readthedocs.io/en/latest/camera Returns the current camera's x and y coordinates. This function is useful for determining the camera's current viewpoint in the world. ```lua local cam_dx, cam_dy = 0, 0 function love.mousereleased(x,y) local cx,cy = camera:position() dx, dy = x-cx, y-dy end function love.update(dt) camera:move(dx * dt, dy * dt) end ``` -------------------------------- ### Player Update Logic with hump.vector Source: https://hump.readthedocs.io/en/latest/vector An example demonstrating how to use hump.vector within a player update function. It handles directional input, normalizes velocity, applies acceleration, caps maximum velocity, and updates player position using vector arithmetic. ```lua function player:update(dt) local delta = vector(0,0) if love.keyboard.isDown('left') then delta.x = -1 elseif love.keyboard.isDown('right') then delta.x = 1 end if love.keyboard.isDown('up') then delta.y = -1 elseif love.keyboard.isDown('down') then delta.y = 1 end delta:normalizeInplace() player.velocity = player.velocity + delta * player.acceleration * dt if player.velocity:len() > player.max_velocity then player.velocity = player.velocity:normalized() * player.max_velocity end player.position = player.position + player.velocity * dt end ``` -------------------------------- ### Damped Camera Smoothing Source: https://hump.readthedocs.io/en/latest/camera Implements damped smoothing for camera movement, where the speed of movement is proportional to the distance from the target. The 'stiffness' parameter determines how fast the camera moves, with higher values resulting in quicker movement. The example shows its use in locking both X and Y positions. ```lua cam.smoother = Camera.smooth.damped(10) ``` ```lua -- warning: creates a function every frame! camera:lockPosition(player.x, player.y, Camera.smooth.damped(2)) ``` -------------------------------- ### Call Parent Constructor in Hump.lua Source: https://hump.readthedocs.io/en/latest/class Explains how to call the parent class constructor from a derived class's constructor using `Shape.init(self, ...)`. This is essential for initializing the parent class's portion of an object. The example demonstrates initializing a `Rectangle` class that inherits from `Shape`. ```lua Class = require 'hump.class' Shape = Class{ init = function(self, area) self.area = area end; __tostring = function(self) return "area = " .. self.area end } Rectangle = Class{__includes = Shape, init = function(self, width, height) Shape.init(self, width * height) self.width = width self.height = height end; __tostring = function(self) local strs = { "width = " .. self.width, "height = " .. self.height, Shape.__tostring(self) } return table.concat(strs, ", ") end } print( Rectangle(2,4) ) -- prints 'width = 2, height = 4, area = 8' ``` -------------------------------- ### Linear Camera Smoothing Source: https://hump.readthedocs.io/en/latest/camera Applies linear smoothing to camera movement, moving the camera towards its target at a constant speed. The 'speed' argument controls how quickly the camera reaches its goal. Be cautious when creating functions every frame, as shown in the second example, for performance reasons. ```lua cam.smoother = Camera.smooth.linear(100) ``` ```lua -- warning: creates a function every frame! camera:lockX(player.x, Camera.smooth.linear(25)) ``` -------------------------------- ### Basic Camera Initialization Source: https://hump.readthedocs.io/en/latest/camera Shows the fundamental way to create a new camera instance using the Camera.new constructor. This function initializes the camera's position and optionally its zoom and rotation. ```lua camera = Camera.new(x, y, zoom, rot) ``` -------------------------------- ### Get Current Gamestate (Lua) Source: https://hump.readthedocs.io/en/latest/gamestate Returns the currently active gamestate. This is useful for checking which state is currently running, for example, before pushing a new state. ```lua function love.keypressed(key) if Gamestate.current() ~= menu and key == 'p' then Gamestate.push(pause) end end ``` -------------------------------- ### Initialize and Use hump.camera in LÖVE Source: https://hump.readthedocs.io/en/latest/camera Demonstrates how to initialize a camera with a player's position and update its movement in the game loop. The camera is attached before drawing game elements and detached afterward. Requires the hump.camera library. ```lua Camera = require "hump.camera" function love.load() camera = Camera(player.pos.x, player.pos.y) end function love.update(dt) local dx,dy = player.x - camera.x, player.y - camera.y camera:move(dx/2, dy/2) end function love.draw() camera:attach() -- do your drawing here camera:detach() end ``` -------------------------------- ### Create Camera Instance Source: https://hump.readthedocs.io/en/latest/camera Creates a new camera instance with optional position, zoom, and rotation. The camera's properties can be accessed via camera.x, camera.y, camera.scale, and camera.rot. The module variable name can be used as a shortcut for new(). ```lua local camera = require 'hump.camera' -- camera looking at (100,100) with zoom 2 and rotated by 45 degrees cam = camera(100, 100, 2, math.pi/2) ``` -------------------------------- ### Get Perpendicular Vector Source: https://hump.readthedocs.io/en/latest/vector-light Returns a vector that is perpendicular to the input vector. This is achieved by a 90-degree rotation and is faster than using vector.rotate with math.pi/2. ```Lua nx,ny = vector.normalize(vector.perpendicular(bx-ax, by-ay)) ``` -------------------------------- ### Get the length of a vector Source: https://hump.readthedocs.io/en/latest/vector Calculates and returns the Euclidean length (magnitude) of the vector. This is computed using the Pythagorean theorem: `sqrt(x^2 + y^2)`. ```lua distance = (a - b):len() ``` -------------------------------- ### Emitting Signals with hump.signal Source: https://hump.readthedocs.io/en/latest/signal This snippet demonstrates emitting signals using Signal.emit() and signal instances. It covers emitting signals with and without arguments, showing how to trigger registered functions and pass data between different parts of the application. ```Lua function love.keypressed(key) -- using a signal instance if key == 'left' then menu:emit('key-left') end end if level.is_finished() then -- adding arguments Signal.emit('level-load', level.next_level) end ``` -------------------------------- ### Get a normalized vector Source: https://hump.readthedocs.io/en/latest/vector Returns a new vector with the same direction as the original vector but with a length of 1. This is achieved by dividing each component of the vector by its length. The original vector remains unchanged. ```lua -- Example usage would typically involve calling this method on an existing vector instance, -- e.g., local normalized_vec = some_vector:normalized() ``` -------------------------------- ### Camera Drawing and Coordinate Transformations Source: https://hump.readthedocs.io/en/latest/camera Includes functions related to drawing with the camera and converting between world and camera coordinate systems. 'draw' accepts a function to execute within the camera's context, and 'worldCoords'/'cameraCoords' perform transformations. ```lua camera:draw(func) camera:worldCoords(x, y) camera:cameraCoords(x, y) ``` -------------------------------- ### Get the squared length of a vector Source: https://hump.readthedocs.io/en/latest/vector Calculates and returns the squared Euclidean length of the vector (`x^2 + y^2`). This is often used for performance optimizations when comparing distances, as it avoids the computationally expensive square root operation. ```lua -- get closest vertex to a given vector closest, dsq = vertices[1], (pos - vertices[1]):len2() for i = 2,#vertices do local temp = (pos - vertices[i]):len2() if temp < dsq then closest, dsq = vertices[i], temp end end ``` -------------------------------- ### Inverting and Chaining Interpolator Functions Source: https://hump.readthedocs.io/en/latest/timer Demonstrates creating new interpolation functions by inverting ('out') and chaining ('chain') existing functions, specifically using 'math.sqrt' as the base. This allows for complex animation curves. ```lua outsqrt = Timer.tween.out(math.sqrt) inoutsqrt = Timer.tween.chain(math.sqrt, outsqrt) ``` -------------------------------- ### Initialize hump.vector Library Source: https://hump.readthedocs.io/en/latest/vector This snippet shows how to require and initialize the hump.vector library in a Lua project. It makes the vector class available for use in subsequent code. ```lua vector = require "hump.vector" ``` -------------------------------- ### Clearing Signals by Pattern with hump.signal Source: https://hump.readthedocs.io/en/latest/signal This snippet demonstrates clearing all functions from signals matching a Lua string pattern using Signal.clearPattern(). This allows for efficient cleanup of multiple related signals at once, for example, clearing all sound-related signals. ```Lua Signal.clearPattern('sound%-.*') player.signals:clearPattern('.*') -- clear all signals ``` -------------------------------- ### Removing Functions from Signals by Pattern with hump.signal Source: https://hump.readthedocs.io/en/latest/signal This snippet shows how to remove functions from all signals that match a Lua string pattern using Signal.removePattern(). This is useful for bulk unregistering listeners, for example, when an object is destroyed or a system is shut down. ```Lua Signal.removePattern('key%-.*', play_click_sound) ``` -------------------------------- ### Draw with Camera Context Source: https://hump.readthedocs.io/en/latest/camera Wraps a drawing function within a camera:attach() and camera:detach() pair, simplifying the process of drawing elements within the camera's coordinate system. ```lua function love.draw() camera:draw(draw_world) draw_hud() end ``` -------------------------------- ### Create Deep Copy of Class Instances with clone() Source: https://hump.readthedocs.io/en/latest/class Illustrates how to create a deep copy (clone) of a class instance using the `Class.clone()` method. Each cloned instance is independent, meaning changes to one clone do not affect others or the original class. This ensures data integrity when creating multiple variations of an object. ```lua Class = require 'hump.class' point = Class{ x = 0, y = 0 } a = point:clone() a.x, a.y = 10, 10 print(a.x, a.y) --> prints '10 10' b = point:clone() print(b.x, b.y) --> prints '0 0' c = a:clone() print(c.x, c.y) --> prints '10 10' ``` -------------------------------- ### Define a New Class in Lua using Hump.lua Source: https://hump.readthedocs.io/en/latest/class Demonstrates how to declare a new class using Class.new() with an initializer function and methods. The 'init' function receives the new object instance and any forwarded arguments. If no constructor is specified, an empty one is used. The class name can be used as a shortcut to Class.new(). ```lua Class = require 'hump.class' -- `Class' is now a shortcut to new() -- define a class class Feline = Class{ init = function(self, size, weight) self.size = size self.weight = weight end; -- define a method stats = function(self) return string.format("size: %.02f, weight: %.02f", self.size, self.weight) end; } -- create two objects garfield = Feline(.7, 45) felix = Feline(.8, 12) print("Garfield: " .. garfield:stats(), "Felix: " .. felix:stats()) ``` ```lua Class = require 'hump.class' -- same as above, but with 'external' function definitions Feline = Class{} function Feline:init(size, weight) self.size = size self.weight = weight end function Feline:stats() return string.format("size: %.02f, weight: %.02f", self.size, self.weight) end garfield = Feline(.7, 45) print(Feline, garfield) ``` -------------------------------- ### Require hump.vector-light Module Source: https://hump.readthedocs.io/en/latest/vector-light This snippet demonstrates how to import the hump.vector-light module in Lua. It's a common first step before using any of the module's functions. ```lua vector = require "hump.vector-light" ``` -------------------------------- ### Set Camera Look At Position Source: https://hump.readthedocs.io/en/latest/camera Sets the camera's position to a specific point (x, y). This is a shortcut for setting camera.x and camera.y directly. To move the camera by a delta, use camera:move(). Chaining with :rotate() is possible. ```lua function love.update(dt) camera:lookAt(player.pos:unpack()) end ``` ```lua function love.update(dt) camera:lookAt(player.pos:unpack()):rotate(player.rot) end ``` -------------------------------- ### Create a new vector using vector() shortcut Source: https://hump.readthedocs.io/en/latest/vector Provides a shortcut to create a new 2D vector by calling the module directly as a function. This is equivalent to using `vector.new(x, y)`. Requires `require "hump.vector"` first. ```lua vector = require "hump.vector" a = vector(10,10) ``` -------------------------------- ### Include Functionality from Tables into Classes Source: https://hump.readthedocs.io/en/latest/class Demonstrates how to copy properties and methods from one table to another using `Class.include()`. This is useful for sharing functionality between objects or classes without direct inheritance. Modifications to included properties in the destination table do not affect the source table. ```lua Class = require 'hump.class' a = { foo = 'bar', bar = {one = 1, two = 2, three = 3}, baz = function() print('baz') end, } b = { foo = 'nothing to see here...' } Class.include(b, a) -- copy values from a to b -- note that neither a nor b are hump classes! print(a.foo, b.foo) -- prints 'bar nothing to see here...' b.baz() -- prints 'baz' b.bar.one = 10 -- changes only values in b print(a.bar.one, b.bar.one) -- prints '1 10' ``` -------------------------------- ### Implement Inheritance with Hump.lua Source: https://hump.readthedocs.io/en/latest/class Shows how to implement single and multiple inheritance using the '__includes' field when defining a class. Single inheritance is achieved by assigning a single parent class, while multiple inheritance involves a table of parent classes. Methods from parent classes are accessible if not overridden in the subclass. ```lua Class = require 'hump.class' A = Class{ foo = function() print('foo') end } B = Class{ bar = function() print('bar') end } -- single inheritance C = Class{__includes = A} instance = C() instance:foo() -- prints 'foo' instance:bar() -- error: function not defined -- multiple inheritance D = Class{__includes = {A,B}} instance = D() instance:foo() -- prints 'foo' instance:bar() -- prints 'bar' ``` -------------------------------- ### Camera Movement and Positioning Functions Source: https://hump.readthedocs.io/en/latest/camera Provides functions for manipulating the camera's view. 'move' adjusts the camera's position by a delta, 'lookAt' centers the camera on a specific coordinate, and 'position' retrieves the current camera coordinates. ```lua camera:move(dx, dy) camera:lookAt(x, y) camera:position() ``` -------------------------------- ### Timer.new() - Create Timer Instance Source: https://hump.readthedocs.io/en/latest/timer Returns a new timer instance that manages its own list of scheduled functions, independent of the global timer. ```APIDOC ## Timer.new() ### Description Creates a new timer instance that is independent of the global timer. It manages its own list of scheduled functions and does not affect or get affected by the global timer. ### Method `Timer.new()` ### Endpoint N/A (Class method) ### Parameters None ### Request Example ```lua menuTimer = Timer.new() ``` ### Response #### Success Response (200) - **timer instance** (object) - A new, independent timer instance. #### Response Example (Returns an object representing the timer instance) ``` -------------------------------- ### Create Deep Copy of Tables with Class.clone() Source: https://hump.readthedocs.io/en/latest/class Demonstrates the usage of `Class.clone()` to create a deep copy of arbitrary Lua tables. This is particularly useful for duplicating complex data structures containing nested tables or functions, ensuring that the copied table is entirely independent of the original. ```lua -- using Class.clone() to copy tables Class = require 'hump.class' a = { foo = 'bar', bar = {one = 1, two = 2, three = 3}, baz = function() print('baz') end, } b = Class.clone(a) b.baz() -- prints 'baz' b.bar.one = 10 print(a.bar.one, b.bar.one) -- prints '1 10' ``` -------------------------------- ### Registering Functions to Signals with hump.signal Source: https://hump.readthedocs.io/en/latest/signal This snippet shows how to register functions to signals using Signal.register(). It covers both simple signal registration and cases where a handle is returned for later removal. It also demonstrates using the colon-syntax with signal instances. ```Lua Signal.register('level-complete', function() self.fanfare:play() end) handle = Signal.register('level-load', function(level) level.show_help() end) menu:register('key-left', select_previous_item) ``` -------------------------------- ### Using Custom Interpolator with Modifiers Source: https://hump.readthedocs.io/en/latest/timer Illustrates how to apply a custom interpolation method, 'in-out-sqrt', to a tween for a circle's radius. This showcases the use of custom functions with predefined modifying prefixes. ```lua Timer.tween(5, circle, {radius = 50}, 'in-out-sqrt') ``` -------------------------------- ### Implement Vertical Camera Locking in Love.update Source: https://hump.readthedocs.io/en/latest/camera Demonstrates how to implement vertical camera locking using the camera:lockX() function within the love.update() function. This ensures the player stays within the horizontal bounds of the screen. ```lua function love.update() -- vertical locking camera:lockX(player.pos.x) end ``` -------------------------------- ### Create New Timer Instance Source: https://hump.readthedocs.io/en/latest/timer Creates a new, independent timer instance that manages its own scheduled functions, separate from the global timer. This is useful when multiple independent schedulers are required. Timer instances use a colon-syntax for calling methods. ```lua menuTimer = Timer.new() ``` -------------------------------- ### List of Functions Source: https://hump.readthedocs.io/en/latest/vector A comprehensive list of functions available for the hump.vector class. ```APIDOC ## List of Functions ### `vector.new(x,y)` Creates a new vector with the given x and y components. ### `vector.fromPolar(angle, radius)` Creates a new vector from polar coordinates (angle in radians). ### `vector.randomDirection(len_min, len_max)` Creates a new vector with a random direction and length within the specified range. ### `vector.isvector(v)` Checks if the given value `v` is a vector. ### `vector:clone()` Returns a copy of the vector. ### `vector:unpack()` Returns the x and y components of the vector. ### `vector:permul(other)` Performs component-wise multiplication with another vector. ### `vector:len()` Returns the magnitude (length) of the vector. ### `vector:toPolar()` Returns the angle (in radians) and radius of the vector. ### `vector:len2()` Returns the squared magnitude of the vector. ### `vector:dist(other)` Calculates the distance between this vector and another vector. ### `vector:dist2(other)` Calculates the squared distance between this vector and another vector. ### `vector:normalized()` Returns a new vector with the same direction but a magnitude of 1. ### `vector:normalizeInplace()` Normalizes the vector in place (magnitude becomes 1). ### `vector:rotated(angle)` Returns a new vector rotated by the given angle (in radians). ### `vector:rotateInplace(angle)` Rotates the vector in place by the given angle (in radians). ### `vector:perpendicular()` Returns a new vector that is perpendicular to this vector. ### `vector:projectOn(v)` Projects this vector onto another vector `v`. ### `vector:mirrorOn(v)` Mirrors this vector across another vector `v`. ### `vector:cross(other)` Calculates the 2D cross product with another vector. ### `vector:angleTo(other)` Calculates the angle between this vector and another vector (in radians). ### `vector:trimmed(max_length)` Returns a new vector trimmed to a maximum length. ### `vector:trimInplace(max_length)` Trims the vector in place to a maximum length. ``` -------------------------------- ### Window-Based Camera Locking with Hump Camera Module Source: https://hump.readthedocs.io/en/latest/camera Describes the camera:lockWindow() function, the most versatile locking method. It locks the camera to a target X,Y position but only moves if the target falls outside a defined screen-rectangle specified in camera coordinates. This enables implementing all other locking methods and off-center locking. ```lua -- lock on player ``` -------------------------------- ### Camera Smoothing Options Source: https://hump.readthedocs.io/en/latest/camera Defines different smoothing behaviors for camera movement. 'none' provides no smoothing, 'linear' uses a specified speed, and 'damped' uses a stiffness factor for more natural motion. ```lua Camera.smooth.none() Camera.smooth.linear(speed) Camera.smooth.damped(stiffness) ``` -------------------------------- ### Move Camera by Delta Source: https://hump.readthedocs.io/en/latest/camera Moves the camera by a given delta (dx, dy). This is a shortcut for updating camera.x and camera.y. To set an absolute position, use camera:lookAt(). Chaining with :rotate() is possible. ```lua function love.update(dt) camera:move(dt * 5, dt * 6) end ``` ```lua function love.update(dt) camera:move(dt * 5, dt * 6):rotate(dt) end ``` -------------------------------- ### Horizontal Camera Locking with Hump Camera Module Source: https://hump.readthedocs.io/en/latest/camera Explains and demonstrates horizontal camera locking using camera:lockX(). It covers locking to a specific X-coordinate in world space, optionally with smoothing, and how to achieve off-center locking by adjusting the target X-coordinate. ```lua -- lock on player vertically camera:lockX(player.x) ``` ```lua -- ... with linear smoothing at 25 px/s camera:lockX(player.x, Camera.smooth.linear(25)) ``` ```lua -- lock player 20px left of center camera:lockX(player.x + 20) ``` -------------------------------- ### Creating and Using Independent Signal Registries with hump.signal Source: https://hump.readthedocs.io/en/latest/signal This snippet illustrates how to create a new, independent signal registry using Signal.new(). This is useful when you need to manage signals separately from the global registry, preventing conflicts and allowing for more encapsulated event handling within specific modules or objects. ```Lua player.signals = Signal.new() -- Using the instance to register and emit player.signals:register('key-left', select_previous_item) player.signals:emit('key-left') ``` -------------------------------- ### Set Default Movement Smoother for Camera Source: https://hump.readthedocs.io/en/latest/camera Shows how to set a default movement smoother for the camera by assigning a Camera.smooth function to the camera.smoother variable. This smoother will be used for camera movements unless overridden. ```lua cam.smoother = Camera.smooth.linear(100) ``` -------------------------------- ### Transform Point to World Coordinates Source: https://hump.readthedocs.io/en/latest/camera Converts a point from camera coordinates (screen space) to world coordinates (game space). This is useful for converting mouse positions or other screen-based inputs into game world positions. ```lua x,y = camera:worldCoords(love.mouse.getPosition()) selectedUnit:plotPath(x,y) ``` -------------------------------- ### Custom Camera Smoothing Function Prototype Source: https://hump.readthedocs.io/en/latest/camera Defines the expected prototype for custom camera smoothing functions. These functions take the delta x and y offsets as input and return the smoothed delta x and y offsets. They are essential for creating custom camera movement behaviors. ```lua function customSmoother(dx,dy, ...) do_stuff() return new_dx,new_dy end ``` -------------------------------- ### camera:mousePosition Source: https://hump.readthedocs.io/en/latest/camera Returns the current mouse position converted to world coordinates. This is a shortcut for camera:worldCoords(love.mouse.getPosition()). ```APIDOC ## camera:mousePosition ### Description Returns the current mouse position in world coordinates. ### Method N/A (This is a function call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```lua x,y = camera:mousePosition() selectedUnit:plotPath(x,y) ``` ### Response #### Success Response (N/A) - **x** (number) - The x-coordinate of the mouse in world coordinates. - **y** (number) - The y-coordinate of the mouse in world coordinates. #### Response Example ```lua -- Example return values x = 620 y = 310 ``` ``` -------------------------------- ### Require hump.timer Module (Lua) Source: https://hump.readthedocs.io/en/latest/timer This snippet demonstrates how to require the hump.timer module in Lua. This is the initial step before utilizing any of its timer-related functionalities. ```lua Timer = require "hump.timer" ``` -------------------------------- ### Simple Rubber-Band Camera Smoother Source: https://hump.readthedocs.io/en/latest/camera A basic implementation of a camera smoother that simulates a rubber-band effect. It uses the delta time to scale the movement, creating a gradual deceleration effect. This can be used to provide a more natural feel to camera movements. ```lua function rubber_band(dx,dy) local dt = love.timer.getDelta() return dx*dt, dy*dt end ``` -------------------------------- ### Zoom Camera by Multiplier Source: https://hump.readthedocs.io/en/latest/camera Multiplies the camera's current zoom level by a given factor. A factor greater than 1 zooms in, less than 1 zooms out. Negative values can mirror and flip. ```lua camera:zoom(2) -- make everything twice as big ``` ```lua camera:zoom(0.5) -- ... and back to normal ``` ```lua camera:zoom(-1) -- mirror and flip everything upside down ``` -------------------------------- ### Register Events and Switch State in Love.js Source: https://hump.readthedocs.io/en/latest/gamestate Demonstrates how to register all game events and switch to a new game state within the love.load() function. It also shows how the love.update() callback is still invoked without explicit calls to Gamestate.update(). ```lua function love.load() Gamestate.registerEvents() Gamestate.switch(menu) end -- love callback will still be invoked function love.update(dt) Timer.update(dt) -- no need for Gamestate.update(dt) end ``` -------------------------------- ### Registering and Emitting Signals with hump.signal Source: https://hump.readthedocs.io/en/latest/signal This snippet demonstrates how to register functions to specific signals and then emit those signals with arguments. It showcases the core functionality of hump.signal for event handling and inter-module communication in Lua. ```Lua Signal.register('shoot', function(x,y, dx,dy) -- for every critter in the path of the bullet: -- try to avoid being hit for critter in pairs(critters) do if critter:intersectsRay(x,y, dx,dy) then critter:setMoveDirection(-dy, dx) end end end) Signal.register('shoot', function() Sounds.fire_bullet:play() end) function love.keypressed(key) if key == ' ' then local x,y = player.pos:unpack() local dx,dy = player.direction:unpack() Signal.emit('shoot', x,y, dx,dy) end end) ``` -------------------------------- ### Convert World Coordinates to Camera Coordinates Source: https://hump.readthedocs.io/en/latest/camera Transforms a point from world coordinates to camera coordinates. This is useful for determining where an object in the game world appears on the screen. It takes the world coordinates (x, y) as input and returns the corresponding camera coordinates. ```lua x,y = camera:cameraCoords(player.pos.x, player.pos.y) love.graphics.line(x, y, love.mouse.getPosition()) ``` -------------------------------- ### Adding Custom Interpolator to Timer.tween Source: https://hump.readthedocs.io/en/latest/timer Shows how to define and add a custom interpolation function, 'sqrt', to the Timer.tween table. This custom function can then be used like any predefined method. ```lua Timer.tween.sqrt = function(t) return math.sqrt(t) end -- or just Timer.tween.sqrt = math.sqrt ``` -------------------------------- ### Class Inheritance Caveats with Metamethods Source: https://hump.readthedocs.io/en/latest/class Highlights a potential issue when subclasses inherit metamethods (like `__add`) from superclasses without overriding them. Operations on subclass instances might result in objects of the superclass type, leading to unexpected behavior or errors when trying to access subclass-specific methods. ```lua Class = require 'hump.class' A = Class{init = function(self, x) self.x = x end} function A:__add(other) return A(self.x + other.x) end function A:show() print("A:", self.x) end B = Class{init = function(self, x, y) A.init(self, x) self.y = y end} function B:show() print("B:", self.x, self.y) end function B:foo() print("foo") end B:include(A) one, two = B(1,2), B(3,4) result = one + two -- result will be of type A, *not* B! result:show() -- prints "A: 4" result:foo() -- error: method does not exist ``` -------------------------------- ### Camera Rotation and Zoom Control Source: https://hump.readthedocs.io/en/latest/camera Details functions for rotating and zooming the camera's view. 'rotate' and 'rotateTo' set the camera's angle, while 'zoom' applies a multiplier and 'zoomTo' sets a specific zoom level. ```lua camera:rotate(angle) camera:rotateTo(angle) camera:zoom(mul) camera:zoomTo(zoom) ``` -------------------------------- ### Register Specific Events and Switch State in Love.js Source: https://hump.readthedocs.io/en/latest/gamestate Illustrates registering only specific game events ('draw', 'update', 'quit') and then switching to a new game state. This is useful for finer control over event handling within the game loop. ```lua function love.load() -- only register draw, update and quit Gamestate.registerEvents{'draw', 'update', 'quit'} Gamestate.switch(menu) end ``` -------------------------------- ### Emitting Signals by Pattern with hump.signal Source: https://hump.readthedocs.io/en/latest/signal This snippet illustrates emitting signals that match a given Lua string pattern using Signal.emitPattern(). This is a powerful feature for broadcasting events to a group of related signals without needing to emit each one individually. ```Lua -- emit all update signals Signal.emitPattern('^update%-.*', dt) ``` -------------------------------- ### Execute Script with Pause Capability Source: https://hump.readthedocs.io/en/latest/timer Executes a script function that can be paused without halting the entire program. The script function receives a 'wait' function as an argument, allowing it to pause execution for a specified delay. This is suitable for animations, splash screens, or repeating tasks with variable delays. ```lua Timer.script(function(wait) print("Now") wait(1) print("After one second") wait(1) print("Bye!") end) ``` ```lua -- useful for splash screens Timer.script(function(wait) Timer.tween(0.5, splash.pos, {x = 300}, 'in-out-quad') wait(5) -- show the splash for 5 seconds Timer.tween(0.5, slpash.pos, {x = 800}, 'in-out-quad') end) ``` ```lua -- repeat something with a varying delay Timer.script(function(wait) while true do spawn_ship() wait(1 / (1-production_speed)) end end) ``` ```lua -- jumping with timer.script self.timers:script(function(wait) local w = 1/12 self.jumping = true Timer.tween(w*2, self, {z = -8}, "out-cubic", function() Timer.tween(w*2, self, {z = 0},"in-cubic") end) self.quad = self.quads.jump[1] wait(w) self.quad = self.quads.jump[2] wait(w) self.quad = self.quads.jump[3] wait(w) self.quad = self.quads.jump[4] wait(w) self.jumping = false self.z = 0 end) ``` -------------------------------- ### Position-Based Camera Locking with Hump Camera Module Source: https://hump.readthedocs.io/en/latest/camera Illustrates position-based camera locking using camera:lockPosition(). This function locks the camera to a specific X and Y coordinate in world space, allowing for precise camera control and off-center aiming by offsetting the target coordinates. ```lua -- lock on player camera:lockPosition(player.x, player.y) ``` ```lua -- lock 50 pixels into player's aiming direction camera:lockPosition(player.x - player.aiming.x * 50, player.y - player.aiming.y * 50) ``` -------------------------------- ### camera:worldCoords Source: https://hump.readthedocs.io/en/latest/camera Transforms a point from camera coordinates to world coordinates. This is useful for determining the game world location corresponding to a screen position, like a mouse click. ```APIDOC ## camera:worldCoords ### Description Transforms a point from camera coordinates to world coordinates. ### Method N/A (This is a function call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```lua -- Assuming you have camera coordinates (cx, cy) -- worldX, worldY = camera:worldCoords(cx, cy) ``` ### Response #### Success Response (N/A) - **x** (number) - The x-coordinate in world coordinates. - **y** (number) - The y-coordinate in world coordinates. #### Response Example ```lua -- Example return values worldX = 500 worldY = 750 ``` ``` -------------------------------- ### Create a new vector using vector.new Source: https://hump.readthedocs.io/en/latest/vector Creates a new 2D vector with specified x and y coordinates. This is the primary constructor for vectors. It takes two numeric arguments for the x and y components. ```lua a = vector.new(10,10) ``` -------------------------------- ### Vector Arithmetic Source: https://hump.readthedocs.io/en/latest/vector Hump provides vector arithmetic by implementing the corresponding metamethods (__add, __mul, etc.). This section details the semantics of these operations. ```APIDOC ## Vector Arithmetic ### Description Hump provides vector arithmetic by implement the corresponding metamethods (`__add`, `__mul`, etc.). Here are the semantics: - `vector + vector = vector`: Component wise sum: `(a,b)+(x,y)=(a+x,b+y)` - `vector - vector = vector`: Component wise difference: `(a,b)-(x,y)=(a-x,b-y)` - `vector * vector = number`: Dot product: `(a,b)⋅(x,y)=a⋅x+b⋅y` - `number * vector = vector`: Scalar multiplication/scaling: `(a,b)⋅s=(s⋅a,s⋅b)` - `vector * number = vector`: Scalar multiplication/scaling: `s⋅(x,y)=(s⋅x,s⋅y)` - `vector / number = vector`: Scalar division: `(a,b)/s=(a/s,b/s)` - `vector // number = vector`: Scalar integer division (only Lua 5.3 and up): `(a,b)//s=(a//s,b//s)` Common relations are also defined: - `a == b`: Same as `a.x == b.x and a.y == b.y`. - `a <= b`: Same as `a.x <= b.x and a.y <= b.y`. - `a < b`: Lexicographical order: `a.x < b.x or (a.x == b.x and a.y < b.y)`. ### Example ```lua -- acceleration, player.velocity and player.position are vectors acceleration = vector(0,-9) player.velocity = player.velocity + acceleration * dt player.position = player.position + player.velocity * dt ``` ``` -------------------------------- ### Switch Gamestate (Lua) Source: https://hump.readthedocs.io/en/latest/gamestate Switches to a new gamestate, passing along any additional arguments to the new state's enter callback. It calls leave() on the current state, replaces it with the new state, and then calls init() (if needed) and enter() on the new state. Processing of callbacks is suspended until update() is called on the new gamestate. ```lua Gamestate.switch(game, level_two) -- stop execution of the current state by using return if player.has_died then return Gamestate.switch(game, level_two) end -- this will not be called when the state is switched player:update() ``` -------------------------------- ### Rotate Camera by Angle Source: https://hump.readthedocs.io/en/latest/camera Rotates the camera by a given angle in radians. This is a shortcut for updating camera.rot. To set an absolute rotation, use camera:rotateTo(). Chaining with :move() is possible. ```lua function love.update(dt) camera:rotate(dt) end ``` ```lua function love.update(dt) camera:rotate(dt):move(dt,dt) end ``` -------------------------------- ### Create a copy of a vector Source: https://hump.readthedocs.io/en/latest/vector Returns a new vector that is a deep copy of the original vector. This is crucial because assigning a vector to another variable creates a reference, not a copy. ```lua a = vector(1,1) -- create vector b = a -- b references a c = a:clone() -- c is a copy of a b.x = 0 -- changes a,b and c print(a,b,c) -- prints '(1,0), (1,0), (1,1)' ``` ```lua copy = original:clone() ``` -------------------------------- ### Convert Vector to String Representation Source: https://hump.readthedocs.io/en/latest/vector-light Generates a human-readable string representation of a 2D vector in the format (x,y). This function is primarily useful for debugging purposes. ```lua print(vector.str(love.mouse.getPosition())) ``` -------------------------------- ### Disable Camera Smoothing Source: https://hump.readthedocs.io/en/latest/camera Sets the camera's smoother to a dummy function that does not perform any smoothing. This is useful when you want the camera to lock instantly onto its target without any interpolation. ```lua cam.smoother = Camera.smooth.none() ``` -------------------------------- ### Scale Vector by Scalar (Division) Source: https://hump.readthedocs.io/en/latest/vector-light Divides each component of a vector (x, y) by a scalar value 's'. The argument order is designed for chaining operations. ```lua x,y = vec.div(self.zoom, vec.sub(x,y, w/2,h/2)) x,y = vec.div(self.zoom, x-w/2, y-h/2) ``` -------------------------------- ### Set Camera Rotation Source: https://hump.readthedocs.io/en/latest/camera Sets the camera's rotation to a specific angle in radians. This directly sets camera.rot. ```lua camera:rotateTo(math.pi/2) ``` -------------------------------- ### Scale Vector by Scalar (Multiplication) Source: https://hump.readthedocs.io/en/latest/vector-light Multiplies each component of a vector (x, y) by a scalar value 's'. The argument order is designed for chaining operations. ```lua velx,vely = vec.mul(dt, vec.add(velx,vely, accx,accy)) ``` -------------------------------- ### Project Vector onto Another Vector Source: https://hump.readthedocs.io/en/latest/vector-light Projects the first vector (x, y) onto the second vector (u, v). It returns the components of the resulting projected vector. ```Lua vx_p,vy_p = vector.project(vx,vy, ax,ay) ``` -------------------------------- ### Create New Gamestate (Lua) Source: https://hump.readthedocs.io/en/latest/gamestate Creates a new, empty gamestate, which is represented as a table. This method is deprecated; the table constructor should be used instead. It can define callbacks for game events. ```lua -- deprecated method: menu = Gamestate.new() -- recommended method: menu = {} ``` -------------------------------- ### Test Vector Partial Lexicographical Order Source: https://hump.readthedocs.io/en/latest/vector-light Tests for partial lexicographical order (<=) between two vectors. It returns true if the first vector's components are less than or equal to the second vector's components, respectively. ```Lua if vector.le(x1,y1, x2,y2) then be.happy() end ``` -------------------------------- ### Register Gamestate Events (Lua) Source: https://hump.readthedocs.io/en/latest/gamestate Overwrites LÖVE's default callbacks to automatically call corresponding Gamestate functions (e.g., Gamestate.update(), Gamestate.draw()). If no argument is provided, it registers all LÖVE callbacks. Existing LÖVE callbacks are still invoked. ```lua local old_update = love.update function love.update(dt) old_update(dt) return Gamestate.current:update(dt) end ``` -------------------------------- ### Set Camera Zoom Level Source: https://hump.readthedocs.io/en/latest/camera Sets the camera's zoom level to a specific value. This directly sets camera.scale. ```lua camera:zoomTo(1) -- reset zoom ``` -------------------------------- ### camera:cameraCoords Source: https://hump.readthedocs.io/en/latest/camera Transforms a point from world coordinates to camera coordinates. This is useful for determining where a point in the game world appears on the screen. ```APIDOC ## camera:cameraCoords ### Description Transforms a point from world coordinates to camera coordinates. ### Method N/A (This is a function call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```lua x,y = camera:cameraCoords(player.pos.x, player.pos.y) love.graphics.line(x, y, love.mouse.getPosition()) ``` ### Response #### Success Response (N/A) - **x** (number) - The x-coordinate in camera coordinates. - **y** (number) - The y-coordinate in camera coordinates. #### Response Example ```lua -- Example return values x = 100 y = 250 ``` ```