Pixel Golang Fundamentals Explained

Author

Reads 359

Programming Code on Laptop Screen
Credit: pexels.com, Programming Code on Laptop Screen

Pixel Golang is a game engine that uses the Go programming language to create 2D games.

It's a lightweight and efficient engine, making it perfect for beginners and indie developers.

Pixel Golang's core is built around a simple and intuitive API, allowing developers to focus on game development rather than engine complexities.

The engine supports multiple graphics drivers, including OpenGL and Vulkan.

Pixel Golang's event-driven architecture makes it easy to handle user input and game logic.

The engine also includes a built-in physics engine and collision detection system.

Pixel Golang's simplicity and ease of use make it a great choice for game development.

Consider reading: Golang Developers

Pixel Basics

Pixel is a hand-crafted 2D game library in Go.

If you're using Windows, you might need to check the wiki's guide on building Pixel, as it can be a bit tricky.

Pixel's features are worth taking a look at to see what it can do.

Curious to learn more? Check out: S Golang

Pixel

Pixel is a hand-crafted 2D game library in Go. If you're using Windows and having trouble building Pixel, please check the guide on the wiki.

IT professional working on a computer in a modern office setting, focused on coding and tasks.
Credit: pexels.com, IT professional working on a computer in a modern office setting, focused on coding and tasks.

You can use Pixel to create images with a specific number of pixels. The number of pixels in an image buffer can be obtained using the Len function, which returns the total number of pixels.

To access a specific pixel, you can use the Get function, which returns the color at the given index. The index of a pixel at a specific position can also be obtained using the Index function.

Setting a pixel at a specific position is done using the Set function, which sets the pixel at x, y to the given color.

On a similar theme: Golang Use Cases

RGBA

RGBA is a color representation that includes alpha-premultiplied red, green, blue, and alpha components within the range of 0 to 1.

This means that RGBA values are floats, unlike color.RGBA, which has a value range of 0 to 1.

You can convert a color to RGBA format using the ToRGBA function, which is preferred over using RGBAModel for performance reasons.

Credit: youtube.com, RGBA color space

The RGBA function returns the alpha-premultiplied red, green, blue, and alpha components of the RGBA color.

You can scale each component of a color by multiplying it with a scale value using the Scaled function.

Colors can be added component-wise using the Add function, and the result is not clamped.

Multiplying colors component-wise is done using the Mul function, and the components are not clamped.

Subtracting colors component-wise is done using the Sub function, and the components are not clamped.

A fully opaque RGBA color can be created using the RGB function, which takes RGB values as input.

You can create a transparent color by multiplying a color obtained from the Alpha constructor with a color created using the RGB constructor.

The NewLinearColor function returns a color based on linear RGB values, which is useful when working with linear colors like those used in RGB LEDs.

Colors can be retrieved from an image using the Get function, which takes an index as input.

From

Computer Program Language Text
Credit: pexels.com, Computer Program Language Text

From pixels to images, it's all about the basics. A pixel is the smallest unit of a digital image, and it's made up of three primary colors: red, green, and blue.

The resolution of an image is determined by the number of pixels it contains. A higher resolution means more pixels, and therefore a more detailed image.

You can think of pixels like building blocks, each one contributing to the overall picture. The more pixels, the more vivid and lifelike the image becomes.

The color depth of an image is measured in bits, with 24-bit color being the most common. This means each pixel can display over 16 million different colors.

The pixel aspect ratio is important for maintaining the image's proportions. A 4:3 aspect ratio is common for older images, while a 16:9 aspect ratio is more suitable for modern screens.

New in v0.29.0

In version 0.29.0, a new function was introduced called NewImageFromBytes.

Illuminated pixel art 'Game Over' sign with vibrant colors against a black background.
Credit: pexels.com, Illuminated pixel art 'Game Over' sign with vibrant colors against a black background.

It creates a new image of a given size using an existing data slice of bytes.

You can now create images from byte slices with this function.

This is a useful tool for working with images in a programmatic way.

The NewImageFromBytes function was added in version 0.29.0.

This update provides developers with a new way to create images programmatically.

On a similar theme: Create a Package in Golang

Geometry and Shapes

With pixel golang, you can easily work with rectangles and lines.

The Edges function returns the four lines that make up the edges of a rectangle, giving you a clear picture of its structure.

You can also get the width of a rectangle using the W function, which is a simple but useful tool for calculations.

The Scaled function on a line scales it around its center point, allowing for smooth transformations.

PictureData has a Bounds function that returns its bounds, while a Line's Bounds function gives you its bounding box as a normalized rectangle.

Credit: youtube.com, Pixel - A Hand-Crafted 2D Game Library In Go

These functions help you understand the spatial relationships between shapes and their components.

In some cases, you might need to create specialized copies of triangles for drawing, which is where the MakeTriangles function comes in handy.

It's a useful tool for creating custom graphics and visual effects.

You can also scale matrices using the ScaledXY function, which allows you to scale objects around a specific point in a precise way.

Rect

A Rect is a 2D rectangle aligned with the axes of the coordinate system.

It is defined by two points, Min and Max, where Max's components are greater or equal than Min's components respectively.

The Rect type has several methods for working with it, including Edges, which returns the four lines that make up the edges of the rectangle.

You can also get the width of the Rect with the W method.

The Union method returns the minimal Rect which covers both r and s, but only if both Rects are normalized.

Vibrant close-up of a computer screen displaying color-coded programming code.
Credit: pexels.com, Vibrant close-up of a computer screen displaying color-coded programming code.

Rects can also be intersected, which returns the maximal Rect which is covered by both r and s, or a zero-rectangle if they don't overlap.

The Vertices method returns a slice of the four corners which make up the rectangle.

The AnchorPos method returns the relative position of the given anchor.

Rects can be normalized, which means their Min and Max points are properly aligned.

If you try to intersect two non-normalized Rects, the Intersect method will return a zero-rectangle.

Rects are useful for working with shapes and geometry in your programs.

Rect Intersect Circle

The Rect Intersect Circle function is a useful tool when working with shapes. It returns a minimal required Vector, such that moving the rect by that vector would stop the Circle and the Rect intersecting.

This function is available in version 0.9.0 and later, and it's a great way to determine the intersection point of a Circle and a Rect. If the Circle and Rect do not overlap, the function returns a zero-vector.

Credit: youtube.com, 2 Circles 1 Rectangle

If only the perimeters touch, the function also returns a zero-vector. But if the Rect contains the Circle, partially or fully, or if the Circle contains the Rect, partially or fully, the function will return a non-zero vector.

Here's a summary of the function's behavior:

  • The function returns a zero-vector if the Circle and Rect do not overlap, or if only the perimeters touch.
  • The function returns a non-zero vector if the Rect contains the Circle, partially or fully, or if the Circle contains the Rect, partially or fully.

This information can be useful in a variety of situations, such as game development or computer graphics. By understanding how the Rect Intersect Circle function works, you can create more realistic and interactive simulations.

MakeTriangles

MakeTriangles is a function that creates a specialized copy of the provided Triangles that draws onto a Batch.

This function is useful for creating multiple triangles on the same Batch without duplicating code.

The MakeTriangles function returns a copy of the provided Triangles, which means you can modify the new copy without affecting the original.

You can use MakeTriangles to create a batch of triangles that all share the same properties.

Men Looking at the Code on the Board
Credit: pexels.com, Men Looking at the Code on the Board

MakeTriangles is a convenient way to create complex geometric shapes by combining multiple triangles.

The function takes into account the properties of the container that the Batch is using, so you don't need to worry about compatibility issues.

If the container doesn't support TrianglesColor, color masking won't work, so be sure to check the container's capabilities before using MakeTriangles.

Here's an interesting read: T Golang

XY

The XY function is a versatile tool in geometry. It returns the components of a vector in two return values.

You can use the XY function to break down a vector into its individual parts, which is helpful when working with complex shapes.

For example, if you have a vector with multiple components, the XY function can help you extract the x and y coordinates separately.

In certain cases, having the x and y coordinates of a vector can be incredibly useful.

NewSprite

NewSprite is a function that creates a Sprite from the supplied frame of a Picture. It's a straightforward process that's easy to understand.

Workplace with modern laptop with program code on screen
Credit: pexels.com, Workplace with modern laptop with program code on screen

You can use NewSprite to create a new Sprite object from a specific frame of a Picture. This is useful when you need to work with individual frames of an image.

NewSprite takes the supplied frame of a Picture as input and returns a new Sprite object. This object can then be used in your code to manipulate the frame.

The NewSprite function is a powerful tool for working with images in your code. It allows you to create new Sprite objects from specific frames of a Picture, giving you more control over your image manipulation.

To use NewSprite, simply call the function and pass in the frame of the Picture you want to use. The function will take care of the rest, returning a new Sprite object that you can work with.

New Linear

L creates and returns a new Line.

The NewLinearColor function returns the given color based on the linear RGB values passed in the parameters.

Close-up of a woman coding using a laptop in an office environment, showcasing modern technology.
Credit: pexels.com, Close-up of a woman coding using a laptop in an office environment, showcasing modern technology.

NewLinearColor is used when the RGB values are actually linear colors, like those in most RGB LEDs.

The input for NewLinearColor is assumed to be in the linear sRGB color space.

NewImage creates a new image of the given size.

A new image can be created with any size, from a small pixel to a large screen.

FillSolid

FillSolid is a powerful tool for creating solid shapes in your geometry projects.

It's especially useful when you need to fill a large area with a single color.

The FillSolid function is often faster than setting individual pixels, making it a great choice for complex shapes.

You can use it to fill an entire image with a solid color, which can be a huge time-saver.

For example, if you're creating a graphic with a background that needs to be a specific color, FillSolid can get the job done quickly.

Get T

The Get T function is a simple yet powerful tool in geometry and shapes. It allows you to retrieve the color at a given index, which is essential for various visual applications.

The Get T function is often used in image processing, where it's crucial to access specific pixels or colors to manipulate or analyze the image.

Matrices and Transformations

Credit: youtube.com, Golang matrix package (2 Solutions!!)

Matrices are a powerful tool in pixel golang for scaling and rotating graphics.

You can scale everything around a given point by the scale factor using the Scaled function.

To apply transformations, you can chain multiple matrices together using the Chained function.

This allows you to build complex transformations by combining simple ones.

When you're done with a transformation, you can use the Unproject function to do the inverse operation to Project.

This is useful when you need to reverse a transformation that was previously applied.

Matrix

A Matrix is a powerful tool in the world of transformations. It allows you to scale, rotate, and project points with ease.

You can scale everything around a given point by the scale factor using the Scaled function. This is particularly useful when you need to resize objects in 3D space.

The Unproject function does the inverse operation to Project, making it easy to reverse the transformation process.

Computer Coding
Credit: pexels.com, Computer Coding

To set a Matrix that every point will be projected by, you can use the SetMatrix function on a Canvas or Batch object.

The Rotated function rotates everything around a given point by the given angle in radians. This is useful for creating animations or transformations that involve rotation.

Chaining multiple Matrices together is also possible using the Chained function. This allows you to apply multiple transformations in a single step, making your code more efficient and easier to read.

Matrices can be used to project points, and the Unproject function can be used to reverse this process. This is a fundamental concept in computer graphics and game development.

Rescale T

Rescaling an image is a crucial operation in image processing, and it's essential to understand its implications. The Rescale function returns a new image buffer based on the original img buffer.

It's worth noting that the contents of the original image are undefined after the Rescale operation. This means you should not rely on the original image's contents after rescaling.

Credit: youtube.com, Matrices and Transformations - Math for Gamedev

Rescaling can also have performance implications, as it will panic if the new image's dimensions exceed the original image's size. This is because the new image's buffer size must be larger than the original image's buffer size.

In general, rescaling is a simple yet powerful operation that can be used to adjust the size of an image. However, it's crucial to be aware of its limitations and potential pitfalls.

Drawing and Rendering

Drawing efficiently is a key aspect of Pixel. The func (*Drawer) Draw method allows for fast drawing of Triangles with Picture onto a provided Target.

Pixel's Batch feature enables drawing of all objects currently in the Batch onto another Target. This makes it easy to create complex graphics without much effort. You can use the func (*Batch) Draw method to draw all objects in the Batch.

The GLFrame's Dirty method marks the GLFrame as changed, which is essential when drawing onto its Frame. The Frame method returns the GLFrame's Frame, where you can draw.

Draw

Opened program for working online on laptop
Credit: pexels.com, Opened program for working online on laptop

Drawing and rendering are crucial aspects of creating engaging visual experiences. The Pixel library provides a range of functions to help you achieve this.

You can draw a Sprite onto a Target using the Draw method, which is equivalent to calling DrawColorMask with a nil color mask. This method allows you to transform the Sprite using a given Matrix.

To draw multiple objects efficiently, use the Batch Draw method, which draws all objects currently in the Batch onto another Target.

If you need to draw triangles with Picture, the Drawer Draw method is the way to go, as it efficiently draws Triangles with Picture onto the provided Target.

Before drawing onto a GLFrame's Frame, don't forget to mark it as changed using the Dirty method.

When you're done drawing, swap buffers and poll events by calling the Update method on the Window object.

Here's a summary of the main drawing methods in Pixel:

Drawmask Inv 0.6.0

Illuminated 'Game Over' sign in pixel art style with neon green and white colors on a dark background.
Credit: pexels.com, Illuminated 'Game Over' sign in pixel art style with neon green and white colors on a dark background.

The DrawColorMask function was added in version 0.6.0.

It draws the Sprite onto the provided Target, transforming it by the given Matrix, and multiplying its color by the given mask.

If the mask is nil, a fully opaque white mask will be used, causing no effect.

(*GLFrame)

The (*GLFrame) is a crucial part of drawing and rendering, and it's essential to understand its functions.

You can use the (*GLFrame) to get the color of a pixel at a specified position, which is exactly what the Color function does. It returns the color of the pixel under the specified position.

The (*GLFrame) also gives you access to its Frame, which is what the Frame function returns. This Frame is what you can draw on.

In other words, the (*GLFrame) is a gateway to the drawing surface, and you can use its functions to get the color of a pixel or draw on the Frame.

From File

Portrait of a young man outdoors in cool pixelated sunglasses and a checkered shirt.
Credit: pexels.com, Portrait of a young man outdoors in cool pixelated sunglasses and a checkered shirt.

Loading images from files is a crucial step in drawing and rendering.

You can use the ImageFromFile function to load an image from a file using the given decoder. This function is added in version 2.3.0.

The ImageFromFile function is useful for loading images directly from files, making it a convenient option for many use cases.

PictureDataFromFile is another function that loads an image from a file using the given decoder, but it converts the image into PictureData. This function is also added in version 2.3.0.

To get started with loading images from files, you'll need to know how to use the ImageFromFile and PictureDataFromFile functions.

In a gallery, we're often working with a collection of images or pictures. A picture represents a rectangular area of raster data, such as a color.

To understand how pictures are displayed, it's helpful to know that they have bounds, which specify the rectangle where data is located.

Make

A rustic rooftop featuring unique pixel art graffiti on a chimney in an urban setting.
Credit: pexels.com, A rustic rooftop featuring unique pixel art graffiti on a chimney in an urban setting.

The "Make" function is a game-changer for artists and designers. MakeTriangles returns a specialized copy of the provided Triangles that draws onto this Batch. It's a powerful tool that can help you create complex designs with ease.

You can use MakeTriangles to create unique and intricate shapes that would be difficult to achieve with a standard Batch. By providing a Triangles object, you can create a specialized copy that suits your specific needs.

The Make function is not limited to Triangles, as evidenced by its versatility. However, for now, let's focus on what we know about MakeTriangles.

Line in 0.9.0

In the latest update, Line has introduced some exciting new features. The Scaled function is now available, allowing you to return the line scaled around the center point.

This is a game-changer for anyone working with lines in their designs. With the Scaled function, you can easily manipulate the size and position of your lines to achieve the desired effect.

One thing to note is that the Scaled function was added in version 0.9.0.

Canvas and Window

Credit: youtube.com, I'm Building a 2D Game in Go (GoLang) - pixelgl

Working with a Canvas in pixel GoLang can be a bit tricky, but understanding its basics is essential. The Canvas Color function returns the color of the pixel at a specific position.

To manipulate the Canvas content, you can use the SetPixels function, which replaces the entire Canvas with a new set of pixels. This function expects an alpha-premultiplied RGBA sequence of a correct length, specifically 4 times the width times the height.

Canvas

The Canvas is a powerful tool that allows you to manipulate pixels on a graphical surface.

You can get the color of a specific pixel on the Canvas by using the Color function, which takes the position of the pixel as an argument.

To replace the entire content of the Canvas with a new set of pixels, you can use the SetPixels function, which requires an alpha-premultiplied RGBA sequence of the correct length.

The length of the RGBA sequence is calculated as 4 times the width times the height of the Canvas.

You can retrieve the current pixels on the Canvas using the Pixels function, which returns an alpha-premultiplied RGBA sequence of the same length as the input for SetPixels.

This sequence can be used to create a new image or to modify the existing pixels on the Canvas.

Window

Close-up view of a programmer typing code on a laptop in a workspace.
Credit: pexels.com, Close-up view of a programmer typing code on a laptop in a workspace.

The Window is a crucial part of any Canvas application. It's where your graphics will be displayed, and it's what users will interact with.

You can update the input on a Window without swapping buffers by calling the UpdateInput function. This is useful for polling window events without disrupting the rendering process.

The SetBounds function allows you to set the bounds of the Window in pixels. However, keep in mind that the actual size of the window will be rounded to integers, even if the bounds are fractional.

You can use the SetBounds function to override the user's attempt to close the Window, or to close the Window from within the program. This can be useful for certain applications where program control is necessary.

Window ComposeMethod

The Window ComposeMethod is a powerful tool for controlling how graphics are combined in a Window.

Setting a Porter-Duff composition method using the SetComposeMethod function allows for more flexibility in drawing onto a Window.

Close-up of a computer screen displaying colorful programming code with depth of field.
Credit: pexels.com, Close-up of a computer screen displaying colorful programming code with depth of field.

This function is used in the following draws onto the Window, making it an essential part of the drawing process.

The SetComposeMethod function is a key part of the Window's drawing capabilities, and understanding how it works is crucial for creating visually appealing and effective graphics.

By setting the composition method, you can control how graphics are layered and combined, resulting in a more polished and professional look.

Recommended read: Golang Graphics

Destroy

Destroying a window is a permanent action. Once you destroy a Window, it can't be used any further.

The Destroy method is a straightforward way to release system resources associated with a Window. This is especially important in memory-constrained environments.

Destroying a Window will prevent you from interacting with it in any way. You won't be able to send events or perform any other actions on the Window after it's been destroyed.

Default Decoder

The Default Decoder is a useful tool for decoding images. It's a DecoderFunc that uses image.Decode to decode images.

Dynamic abstract background featuring computer code in focus with blurred effect.
Credit: pexels.com, Dynamic abstract background featuring computer code in focus with blurred effect.

To use the Default Decoder, you need to import the image formats you want to use. For example, if you want to decode PNG images, you would import _ "image/png".

The Default Decoder is added in version 2.3.0 of the package. This makes it a relatively new feature that you can take advantage of.

You can use the Default Decoder to decode images in your code. Just remember to import the necessary image formats, and you'll be good to go.

Additional reading: Golang Png

Bounds

Bounds are an essential aspect of working with a Canvas and Window. The bounds of a Canvas can be retrieved using the Bounds method of the PictureData type.

The bounds of a PictureData object can be obtained using the Bounds method, which returns the bounds of this PictureData. This method is useful for determining the size and position of the PictureData.

The SetBounds method of the Window type sets the bounds of the Window in pixels. Bounds can be fractional, but the actual size of the window will be rounded to integers.

Credit: youtube.com, How To Pick The Right Canvas Size | Game Dev & Art Tips

The Bounds method of the Line type returns the lines bounding box, which is in the form of a normalized Rect. This method is useful for determining the size and position of the Line.

The bounds of a PictureData object can be retrieved using the Bounds method of the PictureData type. This method returns the bounds of this PictureData, providing a way to determine the size and position of the PictureData.

Input and Events

In pixel golang, you can poll window events without swapping buffers by calling the UpdateInput function. This is a more efficient approach than using the Update method, which invokes UpdateInput.

The UpdateInput function was added in version 0.7.0. Note that it's called UpdateInput, not just Update, so make sure to use the correct method name.

Window UpdateInput inv0.7.0

The Window UpdateInput function was added in version 0.7.0. This function is used to poll window events without swapping buffers.

Young man intensely focused on computer work in a tech office setting with a whiteboard in the background.
Credit: pexels.com, Young man intensely focused on computer work in a tech office setting with a whiteboard in the background.

To poll window events, you can call the UpdateInput function. Note that the Update method invokes UpdateInput, so you can also use Update to poll events indirectly.

UpdateInput is a specific function that allows you to poll window events directly. This can be useful if you need more control over the polling process.

The Update method is a more general function that updates the window and invokes UpdateInput. If you use Update, you don't need to call UpdateInput explicitly.

In practice, you can use either Update or UpdateInput to poll window events, depending on your specific needs.

CursorVisible inv0.6.0

The CursorVisible function is a game-changer for developers working with windows.

The CursorVisible function was added in version inv0.6.0, making it a relatively new addition to the toolkit.

This function allows you to check the visibility status of the mouse cursor with ease.

By using CursorVisible, you can create more intuitive and user-friendly interfaces, as you'll be able to determine exactly when the cursor is visible or not.

Window) Joystick JustPressed Inv

Computer Coding
Credit: pexels.com, Computer Coding

The Window) Joystick JustPressed Inv is a useful function that allows you to determine whether a joystick button has just been pressed down.

It returns a boolean value, which is false if the button index is out of range. This means you need to make sure you're using a valid button index for this function to work correctly.

This function is especially helpful when you're working with joysticks and want to know when a button has just been pressed.

Mouseposition

MousePosition is a crucial aspect of working with windows, allowing you to retrieve the current mouse position within the window's bounds.

The MousePosition method returns the current mouse position in the Window's Bounds, making it a useful tool for various applications.

To get the mouse position, you can use the MousePosition method, which is a part of the Window object.

This method provides a convenient way to track the mouse's movement and position within a specific window.

Brown Gopher Sitting on Brown Soil While Eating
Credit: pexels.com, Brown Gopher Sitting on Brown Soil While Eating

For instance, if you're building a game or an interactive application, you can use MousePosition to detect when the mouse is hovering over a specific area of the window.

The mouse position is returned as a value within the window's bounds, making it easy to work with in your code.

MouseScroll

MouseScroll is a crucial aspect of handling user input in your application. MouseScroll returns the mouse scroll amount in both axes since the last call to Window.Update.

This means you can track how much the user has scrolled their mouse wheel since the last update. The returned values represent the movement in both the x and y axes.

The MouseScroll function is specifically designed to provide accurate and up-to-date information about mouse scroll events.

Mouse Button in v2.3.0

In v2.3.0, a new method was added to check if a button is a mouse button. The IsMouseButton method returns true if the button is one of the mouse buttons.

Male programmers working on computers in a modern office setting, showcasing teamwork and technology.
Credit: pexels.com, Male programmers working on computers in a modern office setting, showcasing teamwork and technology.

This is useful for handling mouse input, and it's a great example of how the API is being improved with each new version.

The IsMouseButton method is a simple but powerful tool that can help you write more efficient and effective code.

With this method, you can easily check if a button press is a mouse button press, and handle it accordingly.

Oscar Hettinger

Writer

Oscar Hettinger is a skilled writer with a passion for crafting informative and engaging content. With a keen eye for detail, he has established himself as a go-to expert in the tech industry, covering topics such as cloud storage and productivity tools. His work has been featured in various online publications, where he has shared his insights on Google Drive subtitle management and other related topics.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.