Mettiti comodo!
Discussions è il tuo spazio in cui puoi conoscere i tuoi colleghi, affrontare insieme le sfide più grandi e divertirti.
- Vuoi vedere gli ultimi aggiornamenti? Segui i punti salienti!
- Cerchi tecniche per migliorare le tue competenze in MATLAB o Simulink? Tips & Tricks è la soluzione che fa per te!
- Vuoi condividere la barzelletta, il gioco di parole o il meme matematico perfetto? Non cercare altro che il divertimento!
- Pensi che ci sia un canale di cui abbiamo bisogno? Raccontaci di più in Ideas
Discussions aggiornate
For the MATLAB One-Button Minihack, I built an ink-wash samurai duel game called ONE BLADE. The contest environment has no audio, runs at around 30 fps, and draws everything inside a fixed axes window. Without a clang or impact sound, two blades meeting on screen can look flat, and it becomes hard for the player to tell right away whether a block or deflect actually landed.
Here are the seven visual techniques I used in the game.
1. Hit-stop
Freeze the entire world for a few dozen milliseconds on impact. When the image suddenly holds for a brief moment, the eye naturally reads that pause as the resistance of two objects colliding.
At the top of update, I check the remaining hit-stop timer and return early if it is above zero, leaving the game clock untouched. If the player presses the button during the freeze, that input is saved in a buffer flag and consumed as soon as the pause ends so no taps are dropped. The screen-shake offset runs before the early return, so the camera still shudders while the scene is frozen and the pause does not look like a lag spike.
2. Screen shake
After a hit, I add a random offset to the camera that decays linearly to zero as the effect nears its end time.
In MATLAB, there is no need to loop through and shift every object on screen. Moving the axes XLim and YLim during rendering shakes the whole scene at once.
3. Ink inversion frames
Fighting games and animation often insert two or three black-and-white inverted frames on a heavy hit, known as impact frames. Since my game already uses black silhouettes on a light paper background, this fits naturally. On impact, I turn on a full-screen black rectangle behind the fighters and flip the characters, slash arcs, and text to white for two or three frames before switching back.
At 30 fps, two or three frames is under a tenth of a second. It goes by too fast to study, but the sudden contrast flip is enough to signal a heavy blow.
4. Screen flash
A full-screen patch sits on top of every other layer, normally fully transparent. On a trigger, its alpha jumps up and fades out quickly. A white flash marks blocks and round transitions, while a red flash marks taking damage. That way the player can read the outcome from the edge of their vision without looking away to check the health indicators.
5. Sparks
At 30 fps, drawing sparks as tiny dots makes it hard to sense how fast they are moving. I store each spark's origin and initial velocity as complex numbers, compute its parabolic path under a gravity of 450, and connect its current position to its position 0.03 seconds earlier. Separating each short streak with NaN lets MATLAB draw all of them in a single line object.
The sparks use three colors to tell exchanges apart. Ink black is for regular blocks and strikes, orange is for deflects and parries, and crimson is for taking a hit or landing the finisher.
6. Impact pose snapping
If character movement relies purely on smooth interpolation, both swings and hits tend to look soft. I keep a table of preset impact poses for deflecting, recoiling, getting cut, and swinging. On the frame of contact, the character snaps straight to the impact pose with no transition, then eases back toward the normal stance like a spring over the next several frames. The sense of force comes mainly from that sudden jump.
7. Camera zoom and slow motion
When the enemy's posture breaks or the finishing cut lands, the camera zooms in by 20% and game time slows down to one-fifth speed, with both easing back to normal over about half a second.
In code, the zoom factor s.zo (which returns from 0.8 to 1.0) also drives the time scale via dt * (4*s.zo - 3), keeping the camera pullback and speed recovery locked together. Hit-stop still counts down in real time rather than scaled time, otherwise a short freeze would get stretched out far too long.
Another week, another fantastic collection of One-Button Games!
We saw some fantastic entries in our STEM Educationcategory:
- Roatis / BRASS & ENTROPY — The Maxwell Experiment
- VMM / How well can you read contour maps?
- JKMSMKJ /QUANTUM COLLAPSE!
- KARUPPASAMYPANDIYAN M / MATLAB MILLIONAIRE
Congratulations!
And our winners in the other categories are:
Originality:
Arcade:
Visualization:
A huge congratulations to all our Week 3 winners!
🏁 The Contest Is Almost Over. Get Your Games Played!
We’ll be recognizing the most-played games, so share your entries with friends, classmates, coworkers, family, and anyone else who might enjoy them.
And there’s something in it for the players too: community members who play and vote have opportunities to win MathWorks swag! 🎁
So spread the word, discover some new games, and vote for your favorites.
This Week's Quiz
104 responses
Which of the following does not return the number of rows of matrix M?
An engineering analysis of Santa's Christmas Flight: inverse perspective mapping, a lane filter with a measurable time constant, and a collision test that cannot tunnel
Introduction
SANTA'S CHRISTMAS FLIGHT draws its scene as pixels in a single image that is updated every frame, with no 3D engine involved. Underneath the snow and presents are three engineering ideas, and this post derives each one and measures it against the game's own code. First, the pinhole camera model: one similar triangles ratio projects every tree, present, and ground row. Second, a first order lag, which makes lane changes smooth and has a time constant you can read straight from the code. Third, a swept collision test, which catches fast presents that a naive test can miss.
Demo

Play it: SANTA'S CHRISTMAS FLIGHT
One button switches lanes in a bouncing pattern: right,middle,left, middle, and so on. Catch presents and orbs, avoid the ice, and fly 40 seconds to the North Pole, where Santa brakes to a stop.
Tips & Tricks
Trick 1: One ratio draws a 3D world
By similar triangles, a point at (X,Y,Z) lands on the image plane at f.X/Z and f.Y/Z. The game uses a focal length of 60 pixels and a camera height of 2.2 units, so a point at lateral x, height y, and depth z appears at column W/2 + f(x-xc)/z and row h0+f(ch-y)/z. Here xc is the camera's sideways offset, and h0=52 is the horizon row. The same focal length sets the field of view: FOV=2.arctan(sensor/2f), which gives 126.9 degrees horizontally and 40.9 degrees above and 54.1 degrees below the horizon for this 240 x 135 image. At Santa's depth of 2, one world unit is 30 pixels, and at depth 18 it is only 3.3.
Trick 2: Run the camera backward to draw the ground
To shade each ground row, set the height to zero and solve for depth: z= ch.f/(row-h0). The game computes this for every row at once with zr=ch*f./((1:H-h0)'). This is the same idea as unprojection, where a pixel is mapped back to 3D by scaling with a known depth. I projected 1,000 random ground points forward and mapped them back, and they returned to within 2.5x10^-14 in depth and 5x10^-15 in lateral position. Resolution is not uniform: each pixel row spans z^2/(ch*f) units of depth, which is 0.03 at depth 2 and 3.0 at depth 20. That is why distant stripes bunch together and why the game fades the far ground into fog.
Trick 3: Size and fog come from the same ratio
A sprite's width and height both scale by f/z, so its pixel area falls as 1/z^2. I tested this with the game's own drawing function and got a log log slop of -2.02 (1,369 pixels at depth 2 against 1,385 predicted, and 16 at depth 18 against 17). Fog is a linear blend between a sprite's color and the sky color, with weight g=min(1,z/18).
Trick 4: One button, three lanes, one low pass filter
The lane rule is ln=ln+dr; if ln~=2,dr=-dr; end, which produces the sequence 3,2,1,2,3,2,1,2 with a single button. Santa's sideways motion follows px=px+(target-px)*min(1,dt*7). That is a first order lag with time constant = 1/7 ~ 0.143 seconds, so a lane change reaches 63% in 0.14 seconds and 95% in 0.43 seconds. The update is an Euler step, so its real time constant depends on the frame rate: 0.134 seconds at 60 fps and 0.116 seconds at 20 fps, which is slightly faster when the game runs slowly. An exact version would use 1-exp(-7*dt). Because the hit radius (1.1) is larger than half the lane spacing (1.8), both neighboring lanes are catchable for about 0.065 seconds while Santa crosses between them.
Trick 5: A swept collision test cannot tunnel
A discrete collision test can miss fast objects, and the inability to detect collisions between fast moving objects passing through each other is called tunneling. The game avoids it with q>2 & s.cz<=2, which asks whether an item crossed the catch plane during the frame. This is a one dimensional version of what sweep based collision detection does, computing impacts along an object's path. I compared it with a naive test that checks whether an item is inside a slab 0.3 units thick, with items moving at 10 units per second. The naive test found 100% of crossings at 60 fps, 90% at 30 fps, and only 60% at 20 fps, where items move 0.5 units per frame. The swept test found 100% at every frame rate.
Trick 6: Brake with a proportional controller
After 40 seconds, the speed command is min(speed,1.5*(zT-3.6)), which means the distance to the stopping point decays exponentially with the time constant 1/1.5=0.667 seconds. My simulation lands in 3.65 seconds, and the closed form prediction is 3.67 seconds: a constant speed phase until the exponential takes over, then the decay.
Live script: the derivations, the code, and the plots
This script covers the notation, the pin hole equations, the inverse ground mapping, a 3D figure of rays meeting the image plane, the depth resolution plot, the sprite area test, fog composting, the lane filter, the lane rule, the double catch window, the swept collision test, the landing controller, and a summary table.
run('SantaFlight_PinholeEngineering.mlx');
Concluding thoughts
Santa's Christmas Flight shows that a convincing 3D scene can come from a few lines of engineering mathematics. A single ratio, f/z, projects the world and sets the size of every sprite. Its inverse recovers depth for each ground row, and a proportional rule brakes the sleigh. A first order lag gives the lane change its feel, with a time constant you can measure. A swept collision test guarantees thst no present is skipped, however fast the game runs.
Each model has limits. The pinhole model is only a first order approximation of a real 3D to 2D mapping, and this game has no lens distortion at all. The Euler lane update makes the response slightly faster at low frame rates, and the exact update 1-exp(-7*dt) would fix that. The swept test checks only the depth plane and a lateral radius, so it is a one dimensional special case of full continous collision detection. These are the next experiments I would suggest: an exact discretization, a time of impact step, and perspective correct shadows.
References
At the present time, the following problems are known in MATLAB Answers itself:
- Symbolic output is not displaying. The work-around is to disp(char(EXPRESSION)) or pretty(EXPRESSION)
- Symbolic preferences are sometimes set to non-defaults
minihackContest.validate
Validating /MATLAB Drive/game.m ...
OK: game() returns a scalar struct.
OK: init, update, render are function handles.
OK: 9751 chars (limit 10000, comments excluded).
OK: no banned functions.
Validation passed.
minihackContest.submit
Title (1-80 chars): ThreeBodyProblemEjector
Publish "ThreeBodyProblemEjector" to contest? [y/N] y
Submitting your entry...
This can take some time - please keep MATLAB open until it finishes.
Submission failed: HTTP 500
Something went wrong. Please try again in a moment.
unsure what to do as runs on matlab online, on matlab22b
The MATLAB One-Button Game Mini Hack is coming to a close. It's been an exciting ride, with so many amazing games submitted by over 80 participants. At the same time, it's been an incredibly rewarding learning experience, with participants gradually refining their entries and experimenting with more intricate graphics along the way. In this article, I'd like to share some of the techniques I've used for ray casting and ray tracing in MATLAB, from the scenery in Canyon Swift to the reflections in Pool 3D.
Ray casting in 2.5D
Ray casting finds which surface is visible in each pixel's direction from the camera. A ray starts at the camera and extends into the scene, with its nearest opaque surface supplying the visible material. When the scene has a regular structure, we can share much of this calculation between neighboring pixels.
Canyon Swift represents its landscape as a height field: each horizontal position has one terrain height. That height can describe a low riverbed, a canyon wall or a tall pillar, but it cannot describe an opening beneath an overhang. Such terrain renderers are often described as 2.5D (or pseudo-3D). Canyon Swift draws the bridges separately, using the terrain's depth to determine which parts remain visible.
Consider one vertical column of the image. All of its viewing directions have the same horizontal bearing, so we can sample the terrain along that horizontal path once, at increasing depths ahead of the camera. Projecting the height of each sample returns the screen row where its top appears. For a level camera, the vertical projection has the following form:
screenRow = horizonRow + focalLength * (cameraHeight - terrainHeight) ./ depth;
Here, screen rows increase downward and focalLength is measured in image pixels. The sample's depth is its forward displacement in the renderer's coordinates, rather than distance along the sloping ray. Terrain above the camera projects above the horizon, and increasing the depth moves its projection closer to the horizon. Canyon Swift turns the view by shifting the horizontal sampling path and banks it by adding a shear to the screen rows.
The game calculates an RGB array with 150 rows and 200 columns. At its default settings, it samples 110 depths for each column, with the samples spaced more closely near the camera. These are shared terrain samples for the whole column, rather than a separate search through the landscape for each of its 150 pixels. An image object created during initialization displays the array; each rendered frame replaces its CData with the newly calculated colors.
In the figure below, the vertical line marks one column of the game's image. Its projected terrain tops are plotted in magenta, ordered by depth from near to far, while the cyan line shows the smallest screen-row value reached so far. The two panels have the same screen-row scale. Each yellow guide connects a marked pixel to the first sample covering it, at the corresponding step in the cyan line:
MATLAB's cummin is used to calculate the running minimum. A farther sample whose top falls below it is hidden by terrain, as the magenta points under the flat end of the cyan line show. A sample that rises above it exposes a new strip of the column. The same front-to-back visibility idea is illustrated in the VoxelSpace reconstruction, where a height map is drawn by updating the uncovered part of each column.
We still need to know which sample colors each pixel. Suppose five terrain samples project to rows 9, 7, 8, 4, 6 in a small image. Their running minima are 9, 7, 7, 4, 4. At screen row 6, the first covering sample is sample 4. From that point onward, every running minimum is at or above row 6, even if a later terrain top falls below it. There are therefore two qualifying minima: the ones for samples 4 and 5. With five samples in total, the first covering sample is 5 + 1 - 2 = 4. More generally, if the count is positive, its index is sampleCount + 1 - count. A count of zero means that no terrain sample reaches the pixel, so it shows the sky. Counting the original tops would result in forgetting which sample arrived first. At row 7, for example, three original tops qualify, giving the incorrect index 5 + 1 - 3 = 3; sample 3 actually projects to row 8. Counting the running minima gives four and correctly selects sample 2.
We can calculate the counts for all rows simultaneously, by taking the ceiling of each running minimum to find the first integer row it covers, counting how many minima arrive at each row, and then accumulating those counts down the screen:
projectedRows = [9; 7; 8; 4; 6];
screenHeight = 10;
sampleCount = numel(projectedRows);
skyline = cummin(projectedRows);
firstRow = min(max(ceil(skyline), 1), screenHeight + 1);
events = accumarray(firstRow, 1, [screenHeight + 1, 1]);
count = cumsum(events(1:screenHeight));
visible = count > 0;
sampleIndex = zeros(screenHeight, 1);
sampleIndex(visible) = sampleCount + 1 - count(visible);
accumarray forms the histogram of first covered rows, and cumsum counts all the minima that have reached each row. The extra bin at screenHeight + 1 holds samples below the image; excluding it keeps those samples from producing a false hit on the bottom row. Tops above the image are assigned to row 1 as they cover the column from its first pixel onward. The visible mask keeps the zero-valued sky entries out of subsequent terrain lookups.
Canyon Swift uses arrays to perform the same calculation for all columns. For each terrain pixel, the selected sample returns its depth. Rearranging the level-camera projection recovers the height of the point seen at that pixel:
worldHeight = cameraHeight - (screenRow - horizonRow) .* depth / focalLength;
For the banked view, the renderer removes the screen-row shear before this calculation. The recovered height varies down a cliff even when several pixels select the same terrain sample: the terrain sample describes the top, while each pixel looks at a different point below it. The rock's horizontal strata are colored using that recovered height, while the sample's terrain values supply its material and shading, and the distance adds atmospheric haze.
Rendering water, scenery, and wraparound landscapes
In Stone Skipping, the lake reflects the mountains and rock stacks that surround it. The landscape is drawn using the same projected-height and running-minimum construction, and its colors are reused for the water, with waves and expanding rings from the skipping stone displacing the reflection:
For each water pixel, the renderer looks up a row above the shoreline and displaces that lookup with waves and rings from the skipping stone. The shoreline is found separately for each column. An additional shoreline calculation omits the rock stacks, allowing their reflections to end and reveal the farther shore behind them.
As the camera travels over the lake, the samples' forward depths change to keep their positions along the lake aligned with the fixed grids. The 100 samples are divided into zones with spacings of 2, 4, 8 and 16 game units. Each sample has a nominal forward depth, baseDepth, and its zone's spacing, step. The camera's progress within the current grid cell is subtracted from that nominal depth:
depth = baseDepth - mod(cameraZ, step);
worldZ = cameraZ + depth;
For example, the first sample in the zone with spacing 4 has a nominal depth of 77. At camera positions 10 and 11, its forward depths become 75 and 74, so both views sample world position 85. When the camera reaches 12, the sample moves to world position 89, the next grid point. This keeps the terrain sampling positions fixed between grid crossings. The renderer samples the terrain at shorter intervals near the camera and at longer intervals farther away.
The camera's position along the lake also sets the time of day in a repeating cycle. Each of four keyframes, for day, sunset, night and dawn, stores a zenith color, a haze color and a light color in one row of a table. interp1 is used to linearly interpolate them between the rows as the cycle wraps around and the keyframes repeat. The sky is blended from the zenith color at the top of the image to the haze color at the horizon, with a weight that grows quadratically with the screen row. The terrain is blended toward the haze color using a weight that increases with depth according to a power law. The light color multiplies the terrain's shading, colors the sun and the clouds, and tints the water and the stone. The water's reflection lookup reads the image after the sky has been drawn, and the sun, the moon and the Aurora Borealis are reflected along with the terrain:
The clouds, the crepuscular rays, the Aurora Borealis and the dawn mist take their variation from a noise tile generated during initialization. rand is used to fill a 256-by-256 array with white noise, and conv2 is used to filter it with a separable Gaussian kernel with a standard deviation of 3 cells, truncated at 8 cells on each side. repmat is used to tile three-by-three copies of the array before filtering, and keeping the central copy makes the result periodic, so lookups can wrap around the tile using mod without visible seams. rescale is then used to map the values to the range 0 to 1:
kernel = exp(-(-8:8).^2/18);
filtered = conv2(kernel, kernel, repmat(rand(256), 3), "same");
noiseTile = rescale(filtered(257:512, 257:512));
Each of these features reads the tile at its own coordinates. Where the tile exceeds 0.5, the clouds shift the sky color toward the light color in proportion to the excess, at a lookup position that drifts with time. For the sun's crepuscular rays, both lookup coordinates are the polar angle around the sun calculated using atan2, scaled so that one turn spans about 256 cells, with an offset that grows with time added to one coordinate and subtracted from the other. The noise is therefore constant along each radius. As the angle varies, the lookup follows a diagonal through the tile, and the offset moves that diagonal perpendicular to itself, so that the rays change in place instead of rotating. Their brightness is multiplied by the positive half of a sine wave with the period of the cycle, which peaks at sunset. The lower part of the Aurora Borealis is a tilted line displaced by two sine waves traveling in opposite directions. Above that, the brightness decays exponentially and is modulated by two columns of the tile scrolling in opposite directions, while the color is interpolated from green at the edge to purple above it. At dawn, the negative half of the same sine wave scales a mist weight: a Gaussian function of each terrain pixel's recovered height, centered on the water level and modulated by the tile and by depth. The terrain is blended toward the haze color with the larger of the mist and haze weights. The sun and the moon are the sum of a narrow and a wide Gaussian, and a logistic step across an offset circle cuts the moon's narrow Gaussian to a crescent. The stars are a separate array, max(0, 60*rand(150, 200) - 59), which lights about one pixel in 60 with a uniformly distributed brightness, and it moves with the view direction using circshift.
Chase the Light! uses a height field wrapped around the inside of a cylinder. Its map coordinates are an angle around the cylinder and a distance along its axis, with one inward terrain height at each map location. The base cylinder has radius 60 game units; the terrain height reduces that radius, raising the land toward the viewer. The camera travels at radius 50, with land continuing around both sides and overhead:
The color and height maps are generated during initialization. In this view, the same patch of the initialized map is shown flat and wrapped onto the inside of the cylinder. The matching circles identify the same hill in both views. The upper part is omitted from the diagram so that the interior remains visible; the game itself closes the landscape overhead.
Here the renderer works along directions radiating from the vanishing point rather than down vertical columns. For each direction, it finds the distance from the camera to the base cylinder in its cross section. The terrain raises the wall inward, so that distance must then be shortened. The game estimates the change by multiplying the terrain height at the base-cylinder intersection by the rate at which this distance changes with the cylinder radius. Subtracting that correction gives a first-order estimate of the distance to the raised wall.
This cross-sectional distance is separate from the forward depth along the cylinder's axis. At each sampled forward depth, the local terrain height gives a corrected cross-sectional distance, which projects to a radial edge in the image in place of the canyon's projected top row. A running minimum and histogram recover the first sample covering each pixel, filling the image inward from its outer regions toward the vanishing point.
The first covering sample identifies the depth interval in which the ray reaches the wall. Within that interval, the renderer approximates the wall profile by a straight segment relating cross-sectional distance to forward depth. It intersects the pixel's ray with that segment and clamps the resulting depth to the interval's endpoints. The refined position supplies the angle and axial coordinate used to look up the terrain color, and the wheels of spokes are drawn separately at their own depths.
Simulating freefall
I've Got Some Falling to Do combines maps of the ground and clouds with a camera that follows the skydiver's descent. The skydiver starts at an altitude of 4,000 m. Gravity accelerates the fall while quadratic drag opposes the motion, gradually reducing the forward speed and bringing the downward speed toward the 217 km/h terminal speed. The trajectory is calculated during initialization in 0.1-second steps, with the positions and velocities stored in a table. During play, the game interpolates this table at the elapsed jump time and adds the sideways motion used to steer through the rings:
The camera initially turns from the airplane door toward the direction of the fall. Its pitch then follows the forward and vertical velocity components, while steering turns and banks the view. A wide-angle stereographic projection supplies a unit-length direction for each pixel, and the camera's orientation transforms these directions into the world. The ray origins follow the skydiver's position, bringing the ground closer and shifting it across the image as the skydiver descends and steers.
The fields, woods, river and roads below are drawn from procedurally generated color maps. Each downward ray meets a horizontal ground plane, and the intersection's coordinates determine which part of the map it sees. The renderer estimates each pixel's footprint on the ground to select a map resolution, using finer maps for nearby ground and evaluating close airfield detail directly. A precalculated map supplies cloud shadows, while distance adds atmospheric haze and the water mixes in color from the sky.
Clouds can partially obscure the scenery below, so the same rays also need to collect cloud color while transmitting some of the background. I've Got Some Falling to Do estimates each ray's segment within the cloud layer between 1,800 and 2,400 m altitude, limiting the search to 14 km from the camera. That segment is split into four sampling intervals. Downward rays use a fixed per-pixel shift within those intervals; upward rays use their midpoints.
At each sample, a precalculated map supplies the cloud's local thickness and lighting. The thickness determines the fraction of the interval inside the cloud, from which the renderer estimates an opacity. Intervals with a greater horizontal extent use more blurred thickness values. Together, the four samples estimate the cloud's transparency along the viewing ray.
Suppose the four sample opacities for one ray are 0.25, 0.5, 0, 0.2, ordered from near to far. Each sample transmits the fraction 1 - alpha of the light arriving from behind it. Multiplying those fractions returns the transmittance through successive sampling intervals:
alpha = [0.25 0.5 0 0.2];
transmission = cumprod(1 - alpha, 2);
weights = [alpha(:,1), transmission(:,1:3) .* alpha(:,2:4)];
Each row represents one ray, so the same operations can be applied to many pixels at once. The nearest sample contributes with a weight of 0.25. The second has 0.5 opacity, but only 0.75 of its light gets through the first sample, resulting in a weight of 0.375. The third sample has 0 opacity, and the fourth results in a weight of 0.075 after transmission through the earlier samples. The sample colors are multiplied by those weights and summed, and the remaining 0.3 of the background color is then added. The weights and remaining transmission add up to 1, accounting for the whole pixel.
Below, the grayscale view shows the total cloud opacity, 1 - transmission(:,4), calculated from the same camera position and ray directions as the frame beside it. The cloud ahead of the skydiver appears as a bright central patch, with darker regions around it where the ground is visible.
The simulated trajectory and steering therefore change both the ground positions reached by the camera rays and the parts of the cloud layer the rays pass through. Below the layer, downward rays reach the land directly, while the continuing descent brings the finer maps and airfield detail into view.
Ray casting in 3D
I've Got Some Falling to Do finds the ground by intersecting downward viewing rays with a plane. In Space Racer 3D, we also need intersections with the curved course and the racing vehicles (anti-gravity Machines). Circular cross sections describe the road as it bends through space and curves upward into a tube, while the Machines are assembled from convex solids. The renderer tests each ray against both kinds of geometry:
The course is defined by circular cross sections along its forward coordinate. At each section, let p be the horizontal displacement from the bottom of the section, q its vertical displacement, and radius the circle's radius. The expression
value = p.^2 + q.^2 - 2*radius.*q;
is zero on the circle, negative inside it and positive outside. Completing the square gives p.^2 + (q-radius).^2 - radius.^2, so the circle's center lies one radius above its bottom. A radius of 100,000 makes the narrow arc used for the open road almost flat, while a radius of 37 defines the inside of the tube.
The camera ray has a direction of the form [x, y, 1], where x and y are the pixel's horizontal and vertical slopes. Its parameter therefore measures forward depth. At each sampled depth, the renderer accounts for the course's bends and evaluates the cross section there. It keeps the first sampled transition from inside to outside, then bisects the interval twice in reciprocal depth: each new test uses the midpoint between the reciprocals of the current endpoint depths. The forward depth is linearly interpolated to estimate where the ray intersects the course surface, and the result is clamped to the refined interval. The course-depth image below uses a logarithmic color scale to make small depth differences along the nearby road easier to distinguish:
Each Machine is built from six convex pieces, with eight bounding planes per piece. A plane's normal points perpendicular to its face. The normal and offset describe the allowed side through dot(normal, point) <= offset. Substituting a point on the ray, origin + t*direction, turns that spatial condition into a bound on t:
dot(normal, direction) * t <= offset - dot(normal, origin)
Dividing by a negative coefficient reverses the inequality, giving a lower bound on t: for example, -2*t <= -12 requires t >= 6. A positive coefficient gives an upper bound, such as 3*t <= 27, or t <= 9. For a ray that is not parallel to any face, we take the largest lower bound as the entry depth and the smallest upper bound as the exit. Lower bounds of 4, 6, 5 and upper bounds of 11, 9, 10, for instance, leave the interval from 6 to 9. The camera is outside the Machines, so the game looks for a nonnegative entry; it rejects a piece if that entry is negative or reaches or exceeds the exit.
Before testing a Machine, the renderer transforms the ray's origin and direction into the Machine's coordinates and leaves the direction unnormalized. Its parameter therefore remains the forward camera depth, matching the course calculation:
The model view uses the game's actual shape, pose and colors. The marked pixel supplies the ray for the interval diagram. The numbered rows show the depths allowed by each plane, and the bottom row is their common interval. In the game, the nearest accepted piece supplies the Machine's surface color, and its depth is compared with the course.
Ray tracing in 3D
Pool 3D uses ray tracing to render reflections on the billiard balls. As the balls separate after a shot, the reflected images of their neighbors move across their surfaces:
The water in Stone Skipping looked up another row of an existing image. Here, the reflected view is calculated from the point on the ball where the camera ray arrives. We first intersect the sphere, find its surface normal at that point, and reflect the viewing direction about the normal. Ray tracing continues from that surface, following the reflected ray to find what appears in the reflection.
A ray can be written as origin + distance*direction. For the sphere calculation below, direction has unit length, so distance measures distance along the ray. Let center and radius describe the sphere. Substituting the ray into the sphere equation gives a quadratic. A negative discriminant means that the ray's line misses the sphere, and a valid intersection must lie in front of the origin. For a camera outside the sphere we use the nearer positive root; a ray starting inside needs the farther positive root. The sphere-intersection derivation in PBRT develops the general quadratic.
For a small numerical example, take a unit sphere at the origin and a camera ray starting at [0.5, 0, 3], pointing along the negative z direction. The ray is offset from the center, so it meets a sloping part of the surface:
origin = [0.5 0 3];
direction = [0 0 -1];
center = [0 0 0];
radius = 1;
offset = origin - center;
b = dot(direction, offset);
discriminant = b^2 - dot(offset, offset) + radius^2;
distance = -b - sqrt(discriminant);
point = origin + distance * direction;
normal = (point - center) / radius;
The distance is 3 - sqrt(3)/2, and the hit point is [0.5, 0, sqrt(3)/2]. Because this sphere has radius 1 and is centered at the origin, the normal has the same coordinates as the hit point. At any true surface hit, the normal is the outward vector from the center to the hit, divided by the radius.
With the unit normal above, reflection reverses the direction's component along the normal while preserving its tangential component:
reflected = direction - 2 * dot(direction, normal) * normal;
For our offset ray, this gives [sqrt(3)/2, 0, 0.5]: it travels sideways and back upward from the hit. The same reflection formula is applied to the ball pixels in Pool 3D.
In the enlarged image below, the reflection of the red ball gives the right edge of the striped ball a pink tint. The schematic shows the balls from the same camera view, with the arrows drawn in the plane of reflection so we can see the angles at P. The camera ray D reaches the striped ball at P, where the radius from the ball's center gives the direction of the outward normal N. The reflected ray R leaves at the same angle to the normal as the incoming ray and reaches the red ball at Q:
The reflected ray repeats the sphere-intersection calculation from P, using R as its direction. Pool 3D tests up to four other balls, chosen by the nearest centers in the table plane, and keeps the nearest valid hit among them. The second ball contributes its color, stripe and simplified lighting. If the reflected ray misses those balls, upward directions see square ceiling lights or the dark room, while downward directions receive the cloth color with a darker region near the ball's foot. These simple environment surfaces fill the remaining reflected directions without intersecting a complete model of the room.
The reflected color is mixed with the ball's locally shaded color using the chosen weight 0.3 + 0.7*(1 + dot(direction, normal))^5. At the point facing the camera, the dot product is near -1 and the reflected fraction is near 0.3. Toward the silhouette, the dot product approaches zero and the reflected fraction approaches 1, making the surroundings more prominent near the ball's edge.
Optimizing ray tracing for speed
With its camera and table fixed, Pool 3D can ray trace the table once and reuse its image during play. During initialization, the renderer takes four subpixel samples for each output pixel and averages each two-by-two group, producing the cached image of the wood, cloth, rail markings and pockets.
During play, each ball is ray traced within a separate 30-by-30 image window, which is positioned over the table using the projected ball center. The images are layered by center depth, with the numbers and soft shadows drawn separately.
The image's alpha mask softens the ball's silhouette. Pool 3D compares the ray's closest distance to the sphere's center with the radius to estimate pixel coverage, keeping a partially covered pixel even when its center ray just misses. That coverage estimate blends the ball image with the layers behind it; it is separate from the true surface hit used in the reflection example.
The ball images are retained between frames. A ball is retraced when its position or orientation changes, when its depth order changes, or when a moving ball is close enough to affect its reflection. The proximity test is limited, so a small reflection of a more distant moving ball can lag behind a full retrace. Even if all 16 balls need to be redrawn, the renderer casts 14,400 camera rays across their windows, compared with 480,000 pixels in the full 800-by-600 view. The renderer can update the balls and their changing reflections while reusing the table image.
And that's all for this article! The MATLAB One-Button Game Mini Hack has been a great opportunity to create and share games, but the fun doesn't have to end with the contest. I hope these examples encourage you to experiment with ray casting and ray tracing in your own MATLAB games moving forward. I'm looking forward to seeing what other games everyone makes in the future!
Dancing Line never stops moving; sumi-e never hurries. I wanted both — and the minihack's one-button rule turned out to be the answer: a brush has no hold and no release, only a touch at the right moment.
So: a short-bristled brush walks a mountain path by itself. Every corner carries a seal. When the seal turns vermilion, tap — and only then does the brush turn. Tap early, the stroke breaks. Miss the corner, it breaks anyway.
The path is a self-avoiding random walk on a lattice, so it turns both left and right, never crosses itself, and is new every round. Colored seals are ink drops: turn correctly and only your next strokes take that color — what's already on the paper never changes.
Tips
- Watch the ring, not the brush. It closes onto the seal; when they touch, tap.
- Wait, don't react. The window is 42% of each segment. Most deaths are early, not late.
- One tap per corner. Never mash — an extra tap before the window kills you.
- Look two corners ahead. The whole path is visible from the start.
- Use the pause. After each new map the brush waits for your tap; read the first two corners before you start.
Round one is as slow as it gets. Somewhere around the fifth corner you stop trying to be fast and start trying to be sure.
A formula driven walkthrough of HELMHOLTZ HERO: closed-form on axis proofs, numerical Biot-Savart, an RMS uniformity score, and a Boris integrated charged probe
Introduction
A Helmholtz pair is two identical circular coils on a common axis. They sit one coil radius apart and carry equal current in the same direction, which makes the magnetic field between them nearly uniform. HELMHOLTZ HERO, my entry for the MATLAB One Button Game Mini Hack, turns Wikipedia,"Helmholtz coil" fact into a game. You lock the coil seperation with one tap and the current ratio with another, and then a charged probe flies through your field. Your score is how uniform you made it. This post shows where each number in the game comes from, step by step.
Demo

Play it: HELMHOLTZ HERO
The physics in plain English
A single current loop makes a field that is strongest at its center and fades along its axis. Put a second loop beside it and the two fields add. If the loops are too close, the field bulges in the middle. If they are too far apart, it dips in the middle. At exactly one radius apart, the bulge and the dip cancel, and the field is flat to a very high order. In the game, you search for that spot with one tap, then try to balance the two currents with the next.
Tips & Tricks
Trick 1:Start from one formula you can start, then test your code against it
A single loop has a simple field along its axis. It falls off as one over (1+z^2) to the power 3/2, in units of the loop's center field. My Biot-Savart code, which sums the field from 96 pieces of each loop, matches that formula to about 2x10^-16. Checking the numerics against a closed form before drawing anything is the single best habit for a physics project. Two loops are just two shifted copies of the same curve, and the code agrees with that sum to the same precision.
Trick 2: Let calculus explain why the coils sit one radius apart
The field of the pair, slid to the middle,is the sum of two single loop curves shift by half the spacing. Its second derivative at the center is proportional to (d^2-1), where d is the spacing in radii, so it vanishes exactly at d=1. That matches the textbook argument that a single coil's on axis field has its inflection point at R/2 from its center, so the coils belong at +/-R/2. At d=1, the center field is 16 squareroot of 5/25, or about 1.4311 times the field of one loop's center. Along the axis, the field stays within 1% of that value out to about 0.31 radii.
Trick 3: Know where your numerical method is trustworthy
The exact field away from the axis is hard: it involves Bessel functions. The game avoids them by averaging the integrand over 96 angles. That is extremely accurate for a periodic integrand, and my tests show differences of about 10^-16 at 0.6 radii from the axis and 10^-9 at 0.9. But very close to the wire (0.05 radii away) the 96 point version is off by about 2x10^-2. That is why the game scores only a small window around the center,0.6 by 0.6 radii. Inside that window, it computes the RMS deviation of the field strength from its center value. The ideal pair scores 0.533% RMS, which maps to a round score of 998 out of 1000.
Trick 4: Move the probe with a royation, not an Euler update
Magnetic fields do no work, so a particle's speed should never change. The Boris method updates the velocity with two cross products. This is the standard rotation step: u^+ = u^- + (u^- + u^- * t) * s, with s=2ft/(1+t^2). It is an exact rotation about the field direction by an angle of 2*arctan|t|, which preserves the speed. Over a full flight in the game, the speed drifted by only about 10^-15. The game then shows three behaviors:
- At d=R, the probe passes through.
- At d=0.4R it is reflected.
- With the second current 1.5 times the first, it is trapped, because the field is strong at the ends and weak in the middle. That is a magnetic bottle: the coils sit farther apart so the field expands in the middle, trapping charged particles.
Trick 5: See the whole game in one 3D plot
Plot the score over the whole range of spacing and current ratio, and you get one sharp peak at d=R with equal currents. That single picture explains the game: every tap moves you across this landscape. The live script draws it, along with a surface showing how the on axis field flattens as the spacing nears one radius. For smooth play, build every graphics object once and only update its data each frame.
Live script: the derivation, the code, and 3D plots
run('HelmholtzHero.m');
Concluding thoughts
HELMHOLTZ HERO shows that a game can also be a verified physics experiment. A closed form on axis formula explains why the coils belong one radius apart, a numerical Biot-Savart sum extends the field off the axis, and an RMS window turns "uniform" into a score. A Boris rotation then moves a charged probe through the result without losing energy. The limits are worth stating: the 96 point integration is only trustworthy away from the wire, the score uses a fixed window, and the probe's step is fixed, not tied to frame time. Next experiments could reverse one coil to make an anti Helmholtz pair. That arrangement gives a nearly uniform field gradient and is used for magnetic traps.
References
Two 25s come together in this special game: my 25th entry in the MATLAB One-Button Game MiniHack competition and the 25th anniversary of MATLAB Central. I wanted to celebrate this occasion with something joyful, colourful and interactive. Instead of simply creating an anniversary animation, I decided to create a birthday party that everyone can actually play.
For 25 years, MATLAB Central has provided a platform for people to share code, ask questions, help one another and learn together. As a small tribute to this community, I designed a 3D birthday cake with 25 candles, one for every year of MATLAB Central, and placed the MATLAB logo at its centre. The golden anniversary badge, rotating rainbow lights, balloons and colourful decorations create the party atmosphere.

Figure 1. The birthday party is ready: 25 unlit candles, an 80-second timer and a colourful 3D scene.
The challenge is simple: light all 25 candles using just one button before the time runs out. The celebration begins when the final candle is lit!
How to play
Tap or click anywhere to start the game. The first tap only starts the 80-second countdown. A moving orb travels around the ring of candles, with a thin beam pointing towards the cake. Normally it is cyan. When it reaches a valid position above an unlit candle, it turns green. Tap at the right moment to light that candle.
Every successful tap reverses the direction of the orb. Its speed increases as more candles are lit, so the timing becomes more challenging. A mistimed tap costs three seconds and makes the orb flash red for 0.6 seconds. The display at the top shows the number of lit candles out of 25 and the time remaining.
There is one more challenge: the wind! The first wind check takes place after five seconds, and later checks occur at short random intervals. A gust can blow out one randomly selected lit candle when 4 to 21 candles are lit. When fewer than four or at least 22 candles are lit, the wind does not extinguish any candles.

Figure 2. A missed tap costs three seconds; the red orb signals the penalty

Figure 3. A wind gust can extinguish a candle, even after successful progress.
Winning, losing and replaying
Light all 25 candles at the same time before the timer reaches zero to win. The remaining time freezes and acts as your score: the more time left, the better. If the countdown reaches zero first, the game displays “TIME UP!”. After either result, tap once to start a fresh round immediately.
Tips and tricks to win
Skip one, then light it on the return
The most useful strategy is the leapfrog technique. Rather than lighting every neighbouring candle in sequence, skip one unlit candle and tap the next one. The orb reverses, so the skipped candle is now the next target on the return journey. Light it, let the orb reverse again, and repeat the pattern. This reduces unnecessary travel across already lit candles. The exact result depends on timing and wind.
Follow the rhythm, not just the colour
The candles are equally spaced at 14.4° intervals. A valid tap must fall within 5.76° on either side of the centre of an unlit candle. The green window is only about 0.14 seconds at the start and 0.11 seconds near the finish. Anticipate the next candle and tap in rhythm instead of waiting to react to the green flash. The orb completes a full lap in about 4.5 seconds initially and 3.3 seconds near the end.Avoid penalties and beat the wind
A wrong tap costs three seconds, so avoid random clicks. Even while the orb is flashing red after a miss, a correctly timed tap can still light a candle. Try to reach 22 lit candles quickly, because the wind stops extinguishing candles from that point onwards. If a gust puts out a candle, treat it as another unlit target and light it when the opportunity comes. Every round begins at the same position and direction, so practising the opening rhythm helps.

Figure 4. Time up with 22 candles lit: just three more were needed

Figure 5. A successful round with all 25 candles lit and 30 seconds remaining.
Behind the game: MATLAB and AI
I developed the entire game in a single MATLAB file using base MATLAB graphics, without external images, sound files or additional toolboxes. I used Claude and ChatGPT as coding assistants to refine the concept, generate and optimize the code, improve the graphics through screenshot-based feedback and keep the implementation within the competition’s character limit.
The program is organized into three main functions: initialization, update and rendering. Functions such as surf, patch, fill3, plot3 and scatter3 create the cake, balloons, candles and decorations. The MATLAB logo is generated using membrane(1) and animated with hgtransform. Trigonometric equations determine the circular orb movement, while HSV-to-RGB colour conversion produces the rotating rainbow lights.
To improve performance, all 25 candles are combined into one patch object, and the flames are combined into another. Their vertices are updated to create smooth growth, flickering and wind effects. The orb moves at 1.40 + 0.02n radians per second, where n is the current number of lit candles. Game states control the start screen, active play, victory and time-up conditions.
The final celebration
Once all 25 candles are lit, four colourful firework bursts appear, the confetti falls four times faster, and the anniversary greeting is displayed. The fireworks expand and fall using mathematical expressions, while the lights and camera continue to animate.

Figure 6. Fireworks and confetti celebrate the successful completion.

Figure 7. Another view of the final anniversary celebration.
Light all 25 candles, enjoy the colourful fireworks and join the anniversary celebration. If you enjoy the game, please give it a like!
I invite everyone to try the game, beat the score and explore my other entries. If you enjoy the games, please give them a like and share your feedback.
Thank you, MathWorks, for organizing this wonderful competition. Happy 25th anniversary, MATLAB Central!
Hello and a warm welcome to everyone! We're excited to have you in the Cody Discussion Channel. To ensure the best possible experience for everyone, it's important to understand the types of content that are most suitable for this channel.
Content that belongs in the Cody Discussion Channel:
- Tips & tricks: Discuss strategies for solving Cody problems that you've found effective.
- Ideas or suggestions for improvement: Have thoughts on how to make Cody better? We'd love to hear them.
- Issues: Encountering difficulties or bugs with Cody? Let us know so we can address them.
- Requests for guidance: Stuck on a Cody problem? Ask for advice or hints, but make sure to show your efforts in attempting to solve the problem first.
- General discussions: Anything else related to Cody that doesn't fit into the above categories.
Content that does not belong in the Cody Discussion Channel:
- Comments on specific Cody problems: Examples include unclear problem descriptions or incorrect testing suites.
- Comments on specific Cody solutions: For example, you find a solution creative or helpful.
Please direct such comments to the Comments section on the problem or solution page itself.
We hope the Cody discussion channel becomes a vibrant space for sharing expertise, learning new skills, and connecting with others.
MATSTAR : Mission to the Moon by NRF
One button. One mission. Reach the Moon
I created MATSTAR: Mission to the Moon, a one-button space game for the MATLAB Mini Hack.
The player controls a spacecraft travelling from Earth toward the Moon. The objective is to collect stars, avoid asteroids, and complete the lunar mission using simple controls.
About the MATLAB Code
I developed the game using MATLAB functions and a structured game-state approach.
The main function, game, acts as the entry point and connects the three core parts of the game:
function g = game()
g.init = @initState;
g.update = @updateState;
g.render = @renderFrame;
end
This structure separates the game into three stages:
- Initialization (initState) — Sets up the initial game state, including the spacecraft position, velocity, score, shield, and game status.
- Update (updateState) — Handles gameplay logic such as spacecraft movement, gravity, boost controls, star collection, asteroid collisions, and mission progress.
- Rendering (renderFrame) — Draws the game scene, spacecraft, stars, obstacles, and mission information.
I also used local functions to keep the code organized and easier to maintain.
Gameplay Features:
- Spacebar or mouse-click boost control
- Gravity-based spacecraft movement
- Star collection and scoring
- Asteroid collision detection
- One shield for protection
- Boundary bounce mechanics
- Mission progress from 0% to 100%
- Lunar landing and victory condition
Tips & Tricks I Learned
- Keep the code modular: Separating initialization, updates, and rendering makes the game easier to understand and debug.
- Manage the game state carefully: Variables such as display, position, velocity, score, shield, and mission status need to be updated consistently.
- Test gameplay in small steps: Start with movement, then add obstacles, scoring, and collision logic.
- Use validation before submission: Check the required function structure, function handles, character limit, and restrictions before publishing.
- Keep the gameplay simple: A one-button control scheme can still create an engaging challenge when combined with gravity, obstacles, and timing.
MATSTAR was a fun way to explore MATLAB game development while combining programming logic, physics-inspired movement, and space-themed creativity.
The motivation behind the game
I was inspired by a classroom activity in which students learned mathematics through a tug-of-war competition. I really liked the idea of combining learning, competition and fun. As a faculty member, I wanted to bring a similar experience into the classroom using MATLAB. The MATLAB One-Button Game Mini Hack gave me a wonderful opportunity to turn this idea into an interactive quiz game, where knowledge and quick thinking determine the strength of each team.Watch the original classroom activity on Facebook.

The starting screen of MATLAB Brain Battle.
How I implemented the game
I created a question bank of 50 MATLAB questions covering arrays, indexing, matrix operations, mathematical functions, plotting and programming basics. The game uses randperm to shuffle the questions and answer choices, making each replay different. The player and the simulated MATLAB opponent receive the same question bank in different orders and answer independently.
I divided the game into initialization, update and rendering functions. The update function manages the timers, answer checking, scores and rope movement. I used MATLAB graphics such as patch, plot, rectangle and text to create the arena, animated players and quiz panels, without needing external graphics files.
How to play and the rules
Click to start the game. You control the blue team, while MATLAB controls the red team. Click directly on one of the four answer choices in the blue panel. You have 15 seconds to answer each question. A correct choice turns green, an incorrect choice turns red, and the correct answer is displayed after a mistake or timeout. MATLAB answers its own questions automatically.

Both teams answer independently.

A correct answer earns pulling force.
Every correct answer earns between 1 and 2 pulling units, depending on how quickly it is answered. Wrong answers and timeouts earn no pulling force. The rope moves according to the difference between the teams’ cumulative pulling forces. A team wins immediately when its advantage reaches 20 pulling units. If both teams finish all 50 questions without reaching that boundary, the team with more correct answers wins; total pulling force breaks a tie. Click to replay after the result. The best score is retained during the current session.
Tips and tricks for developing a similar game
Start with a small question bank and keep the game logic separate from the graphics. Store each question with its correct answer and three distractors in a cell array. Randomize the answer positions, but keep track of the correct option before evaluating a click. Use a timer to reward both accuracy and speed. In my game, the pulling force is calculated as 1 + max(0, 1 − elapsed time/15), so faster correct answers receive a higher reward. I also used a gradual update of the rope position to make the movement smoother.
To work within the contest character limit, reusable drawing functions and compact graphics commands are useful. For example, the same player-drawing function is used for all four characters, with changes in position, direction and team colour. For classroom use, the question bank can be replaced with questions from any subject without changing the main game logic.
Learning through competition

Instant feedback helps learners identify mistakes and review the correct answer.
The main idea is to make a simple quiz more engaging. Instead of answering questions only to earn marks, students can see the direct effect of their answers through the movement of the rope. The immediate feedback gives them an opportunity to correct their mistakes, while the competition encourages them to recall concepts quickly. For classroom activities, the time limit and the simulated opponent’s speed and accuracy can also be adjusted to suit the learners’ level.
An invitation to fellow faculty members
I would like to encourage fellow faculty members to explore this kind of gamification in their classrooms. It does not have to be a complex game. Even a simple activity based on a course question bank can make revision, formative assessment and classroom interaction more enjoyable. The same concept can be adapted to mathematics, engineering, programming or any other subject. I am excited to try this game with my students in the coming semester and observe how they respond to this approach.
I invite everyone to try MATLAB Brain Battle, share your feedback, and explore how similar games can be used in teaching and learning. Thank you, MathWorks, for providing this wonderful opportunity to bring creative ideas into practice!Play MATLAB Brain Battle on MathWorks.
When I first started developing games for the MATLAB One-Button Game MiniHack competition, my biggest challenge was to create interesting and engaging games using just one button. Most traditional games require multiple controls for movement and other actions. Initially, I struggled to find suitable game concepts, but gradually, I started exploring different possibilities to make effective use of the single-button option.
I used Claude and ChatGPT as AI coding assistants throughout the game development process. For each game, I first developed a concept, visualized the expected output and defined the gameplay, rules, scoring system and user interactions. I then provided detailed prompts to these AI tools to convert my ideas into MATLAB code.
The initial outputs were not always as expected. I followed an iterative development approach by testing the generated code, sharing screenshots, providing specific feedback and correcting errors. I used techniques such as detailed prompting, reference-based prompting, step-by-step development and AI-assisted debugging to continuously improve the graphics, animations and gameplay. I also explored alternative coding approaches.
From a technical perspective, I used separate initialization, update and rendering functions to manage game operations. State-based programming was used to manage different stages of the game. MATLAB functions such as patch, surf, plot3 and hgtransform were used to create 2D and 3D graphics. Trigonometric functions, rotation matrices, coordinate transformations and mathematical equations were used to generate movements and animations. I also implemented randomization, collision detection, scoring mechanisms and dynamic difficulty based on the requirements of each game.
To make effective use of the one-button option, I automated certain game operations and allowed the player to control the most important action. I implemented techniques such as automatic movement, timing-based interactions, visual indicators, automatic cycling through available options and context-based controls. Depending on the game situation, the same button performs different actions, making the games simple to play while requiring concentration, timing and decision-making.
Another major challenge was developing visually attractive games within the character limit specified by the competition. I used alternative programming approaches, vectorization, reusable functions, simplified mathematical expressions and compact graphics operations. Several iterations of code optimization and testing were carried out to reduce the character count while retaining the gameplay and visual quality as much as possible.
My Learning Experience
This competition helped me understand the importance of combining human creativity, mathematical knowledge, programming skills and artificial intelligence.
AI helped me accelerate the development process, but defining the problem, selecting the right approach, making decisions, testing the output and improving the gameplay required continuous human involvement.
One of my biggest learnings is that the quality of AI-generated output depends significantly on how clearly we communicate our ideas and how effectively we evaluate and refine the results.
Thank you, MathWorks, for organizing this wonderful competition and providing a platform to explore creativity and innovation
I invite you all to check out my entries in the MATLAB One-Button Game MiniHack competition. Please try playing the games and explore the different gameplay concepts. If you enjoy playing the games, please give them a like and share your feedback.
Explore and play all my entries:
Happy Gaming!
In my previous game (Quantum Collapse!), I decided to represent a quantum particle as a point after measurement just like a classical particle for "comparison" purposes. But a more accurate depiction would be the original spread-out wavefunction being localized at a specific position (as a δ-function). So in the new version of the game (Quantum Collapse! 2) I have incorporated this conceptual shift along with a few more game-y upgrades / changes:
- The probability of the quantum particle being found inside the capture (measurement) zone is prominently displayed at the top of the zone, as a "visual" equivalent to the classical ball's obvious position (one of my daughter's most vehement request!).
- The capture (measurement) zone now moves at varying speeds as the game plays out, making it slightly trickier to time the tap.
- As the quantum wavefunction collapses in response to a tap, a ring-burst emerges from the location of the δ-function "visualizing" the tap forcing a measurement.
- More score points are awarded if one has a quick eye-finger coordination!
- Revised outcome texts which make more sense (I think) and the final verdict (collocations related to new physicists) now accompanies stats summary like final score, accuracy, highest energy reached, longest time spent in an energy level, etc.
Give this sequel a go and see if you can do better than my nⁿ-th attempt.

Well, that is all for this contest season from me. Thanks to all the participants and organizers (@Adam Danz, @Chen Lin, @David, @Matt Tearle, @Mike Croucher, @Ned Gulley, @Stephen23) of this grand event.🎉
Happy Thanksgiving and Season's Greetings! 🍂🍁❄️☃️
What happens when you turn an engineering concept into a one-button game?
That was the idea behind PISTON PULSE: The Diesel Timing Challenge, a MATLAB game inspired by my interest and practical experience with heavy-duty diesel engines.
The goal was to create something simple to play but connected to a real engineering concept.
HOW THE GAME WORKS
PISTON PULSE features an animated piston, connecting rod and crank mechanism alongside a circular timing gauge.
The gauge represents the four strokes of a four-stroke engine: Intake, Compression, Power and Exhaust.
A white indicator rotates around the gauge, while a green segment marks the target zone. The player's task is to press the SPACEBAR at the right moment as the indicator reaches that zone.
The game rewards accurate timing with points. As players progress, they face a greater timing challenge.
THE ENGINEERING CONNECTION
The game draws inspiration from the importance of fuel injection timing in diesel engines.
In actual diesel engine operation, injection timing influences the combustion process and overall engine performance.
PISTON PULSE simplifies this engineering concept into an interactive challenge, giving players a fun way to engage with engine timing and the four-stroke cycle.
CONCLUSION
Building PISTON PULSE gave me an opportunity to bring together my mechanical engineering background, practical experience and growing interest in MATLAB programming.
It is a small project, but one that reminds me that engineering concepts can be explored in creative and interactive ways.
Developed with MATLAB for the One-Button Game Minihack.
An analytic solution for a 4-joint arm with a three finger gripper, verified against forward kinematics and implemented in under 10,000 characters
Introduction
Inverse kinematics sounds like a graduate topic, but you do it every time you reach for a cup. Your brain works out how far to turn your shoulder and bend your elbow so your hand lands on the cup. A robot has to do the same arithmetic. In KINEMATIX 3D, a one button game for the MATLAB One Button Game Mini Hack, that arithmetic becomes the game. You tap three times to choose where a three finger robot hand should go: once for direction, once for distance, and once for height. The game then solves the joint angles with a closed-form formula and moves the arm there. It closes the fingers around a glowing ball and drops it in a bin. I checked the formula against 20,000 random targets, and the hand landed within about 5x10^-16 meters of each one, which is about the rounding limit of double-precision arithmetic.
Demo

Play it: KINEMATIX 3D: Aim the Claw
The first tap locks the direction when the cyan laser points at the ball. The second tap locks the reach when the pink marker sits on the ball's floor ring. The third tap locks the height, and a live readout showed how far you are from the ball. After that, the arm solves, reaches, grips, and carries the ball to the bin, while a floating score pop-up and a screen flash report the result.
The arm in plain English
The arm has four joints: a base that turns, a shoulder, an elbow, and a wrist. The wrist is always adjusted so the hand points straight down, like a claw machine. The forward problem is easy: give me the joint angles and I can find where the hand is. The game needs the reverse: given the point you choose, find the joint angles.
Tips & Tricks
Trick 1: Turn first, then solve a flat problem
Every target has a direction around the base, a horizontal distance, and a height. Turning the base to face the target handles the direction. After that, the shoulder, elbow, and wrist all move in one vertical plane, so you only need the distance and height. In MATLAB, atan2 finds the direction, and it returns the four quadrant inverse tangent, so it keeps working when the target is behind or beside the base. hypot finds the distance, and it avoids underflow and overflow. Because the hand points down, the wrist has to sit one hand length above the grasp point.
Trick 2: Let a triangle find the elbow
The shoulder, elbow, and wrist form a triangle with three known sides: the two links and the straight line from shoulder to wrist. A triangle's angles are fixed by its sides, which is the law of cosines. In vector form it is a dot product: when two vectors meet at angle, the square of their sum grows with the cosine of that angle. Inverting it gives the elbow angle. It gives two answers, because a two link chain generally has two solutions, often called elbow up and elbow down. The game picks elbow up and it clamps the cosine to between -1 and 1 so acos never fails.
Once the elbow bend is known, the arm is a rigid shape. The direction to the wrist is the upper arm's direction plus a fixed offset angle, so the shoulder angle is the direction to the wrist minus that offset. This is a rotation matrix argument. The textbook two link derivation does it in the same order: the elbow angle is computed first, and then the shoulder angle. Finally, the three angles must add up to -90 degrees so the hand stays pointing down.
For a worked example, take the target (0.8,0.3,0.5). The solution is a yaw of 20.6 degrees, a shoulder of 70.8 degrees, an elbow of -103.2 degrees, and a wrist of -57.6 degrees. The live script below does this step by step.
Trick 3: Draw it in 3D
A figure is the fatest sanity check. A dashed line on the floor shows the target's distance and direction, and a vertical stem shows its height. The arm's links sit above them at the solved angles, and the short vertical hand shows the wrist condition.
Trick 4: Prove it with forward kinematics
The forward direction is easy: add up the links using rotation matricies. Feeding the inverse solution back through forward kinematics should return the original target. I tried this on 20,000 random targets in the game's aim box, and the target miss was about 5x10^-16 metres. For that box, the elbow cosine stayed between about -0.67 and 0.24, safely inside the legal range of -1 to 1, so every target is reachable.
Trick 5: Keep the animation smooth and flicker free
I learned four things the hard way:
- Create each graphics line once, then only update its coordinates every frame.
- Blend the joint angles with a smooth curve. The hand stays level automatically, because the three angles add up to -90 degrees at both ends and a straight blend keeps that sum, so the claw's path curves but never tilts.
- Detect a button press,not a hold, so one tap is one action.
- Never draw two coincident lines to fake a highlight. In 3D they fight over deoth and the arm shimmers, which my first version did while troubleshoiting the code.
Live script: the proof, the code, and 3D plots
run('KINEMATIX3D_Inversekinematics.m');
Concluding thoughts
Inverse kinematics does not always need an iterative solver. For this arm, a dot product and a rotation matrix give the elbow and shoulder in closed form, and forward kinematics verifies the answer to rounding precision. A one button game turns that algebra into something players can feel: each tap fixes one coordinate, and the solver does the rest.
The method has limits. It handles one elbow up branch, assumes a vertical grasp, and ignores joint limits. For general robots, Mathworks' Robotics System Toolbox goes further: its inverseKinematics solver is gradient descent based, and its documentation points to analyticalInverseKinematics for closed form solutions. Try changing the link lenghts or the aim box and rerun the live script. Or add the elbow down branch by flipping one sign.
References
INTRODUCTION
When I came across the MATLAB One-Button Game Mini Hack, I wanted to approach it from an engineering perspective.
As a Mechanical Engineering student with practical experience around heavy-duty diesel engines, I decided to build something inspired by a subject I was already familiar with: diesel engine operation and fuel injection timing.
That idea became PISTON PULSE: The Diesel Timing Challenge.
The game combines an animated piston-and-crank mechanism with a circular timing gauge. The player's task is to observe the rotating indicator and press the SPACEBAR at the right moment to achieve a successful injection.
Developing this game taught me several useful lessons about MATLAB programming, game development and working with AI coding assistants. Here are some of them.
1. START WITH A CONCEPT YOU UNDERSTAND
Rather than choosing a random game idea, I drew inspiration from the operation of a four-stroke diesel engine.
My engineering background helped me decide on the theme and understand the mechanical components I wanted to represent.
I would recommend starting with a subject you understand or genuinely find interesting. It makes the development process more meaningful and gives you a better foundation for evaluating the result.
2. USE AI AS A DEVELOPMENT PARTNER
I used Claude AI to assist with the development of PISTON PULSE.
However, I learned that generating code is only one part of the process. You still need to understand the concept, communicate your expectations, test the output and identify areas that need improvement.
I approached the project by discussing the game concept, reviewing the generated implementation and testing it in MATLAB.
My biggest lesson here is that AI can accelerate development, but you still need to guide the process and take responsibility for the final result.
3. UNDERSTAND THE STARTER PROJECT'S STRUCTURE
One of the most important things I learned was understanding the structure required by the competition.
The starter project uses three main function handles:
g.init = @initState;
g.update = @updateState;
g.render = @renderFrame;
Each function has a specific responsibility:
- initState initializes the game and creates the graphics objects.
- updateState handles the game logic, movement and button input.
- renderFrame updates the graphics based on the current game state.
Understanding this structure helped me appreciate why the competition provides a starter project instead of allowing participants to submit just any standalone MATLAB script.
4. MAKE THE ONE-BUTTON INPUT MEANINGFUL
The competition has a simple but important restriction: the player can only use SPACEBAR or a mouse click.
For PISTON PULSE, I made the SPACEBAR the fuel-injection control.
The challenge is not simply pressing a button. It is deciding when to press it based on the timing indicator.
Another important detail is that the framework provides an edge-triggered input through the pressed variable. This means the game receives a signal for each tap rather than continuously detecting whether a key is being held down.
Understanding this helped me design the gameplay around deliberate timing.
5. USE DT FOR TIME-BASED MOVEMENT
The update function receives dt, which represents the time elapsed between frames, in seconds.
A useful practice is to scale movement by dt rather than moving an object by a fixed amount every frame.
For example:
state.x = state.x + state.speed * dt;
This makes movement depend on elapsed time rather than the number of frames processed.
It is an important consideration when developing games that should behave consistently across different computers.
6. CREATE GRAPHICS ONCE AND UPDATE THEM
Another useful lesson from the starter project was the importance of graphics management.
Instead of repeatedly deleting and recreating graphics objects during gameplay, create them during initialization and update their properties during rendering.
For example:
% Create the object during initialization
state.player = rectangle(ax, ...
'Position', [400 300 30 30]);
% Update its position during rendering
state.player.Position = [state.x state.y 30 30];
This approach avoids unnecessary graphics operations and is particularly useful when developing animated games.
7. TEST AND VALIDATE YOUR GAME
I also learned that a game working as a normal MATLAB script does not automatically mean it satisfies the competition requirements.
It is important to test it using the actual competition framework.
The starter project provides these commands:
minihackContest.validate
minihackContest.play
The validation command checks the game against the competition requirements, while play allows you to test the game locally.
I found this particularly useful because it allowed me to identify whether my implementation followed the expected framework before submitting it.
MY BIGGEST TAKEAWAY
Developing PISTON PULSE has been a valuable learning experience.
I started with an engineering concept and gradually turned it into a working one-button game using MATLAB, with AI assistance along the way.
As someone still developing my MATLAB programming skills, completing this project has shown me how much can be learned by taking an idea, experimenting with it and improving it through testing.
My advice to other participants is simple: start with an idea you understand, learn the framework, make the gameplay interesting and don't be afraid to experiment.
I hope someone finds these lessons useful!
PROJECT: PISTON PULSE: The Diesel Timing Challenge
TOOLS: MATLAB and Claude AI.
When I started developing a game for the MATLAB One-Button Game MiniHack, my biggest challenge was deciding how to control a Rubik’s Cube with just one button. A normal cube needs several different moves, and each face can be turned in two directions. How could I give the player these choices with a single click?
I realised that the button did not have to select the face and direction directly. Instead, the game could automatically cycle through the available moves, and the player could click at the right moment. This became the main idea behind my One-Button Cube.

The starting screen with the solved cube.
How I used AI to develop the game
I used an AI tool as a coding assistant to turn my idea into MATLAB code. I described the cube, the one-click restriction, the automatic scramble and the visual guidance I wanted. I refined the approach through prompts, focusing on the game logic, graphics and player experience. The AI helped translate these requirements into functions and mathematical operations. The key was to give clear instructions rather than simply ask for a cube game.
How I implemented the cube in MATLAB
The cube is built from 27 small cubes arranged in a 3 × 3 × 3 grid. Each small cube has a position and a rotation matrix. Coloured stickers are placed on the outer faces. MATLAB patch objects display the cube, while a mathematical camera projection, depth sorting and lighting calculations give it a 3D appearance.
For each turn, the code selects the nine small cubes on the chosen face and rotates them smoothly by 90 degrees. At the end of the animation, the rotation is rounded to exact integer values to avoid numerical drift. The game uses three main functions: init to create the scene, update to handle moves and timing, and render to display the cube and messages.

The cube automatically scrambles at the start of a level.
Making one click do more
I limited the available moves to the red, blue and white faces, with clockwise and counter-clockwise turns for each. The game automatically cycles through these six choices. It stores the reverse of each scramble move in a list, so it knows which move should be undone next. A green highlight identifies that move; yellow indicates that the player should wait.
The same click starts the game, applies a selected move and advances to the next level. A short grace period of up to 0.3 seconds after the correct highlight helps players who click slightly late. This design avoids extra buttons and makes timing the main challenge.
How to play
- Click to start and watch the cube scramble automatically.
- Wait while the highlight cycles through the six possible moves.
- When the outline and arrow turn GREEN and “TAP NOW!” appears, click once.
- Repeat until the cube is solved. Click again to start the next level.

Yellow highlight: wait for the correct move.

Green highlight: click to apply the correct move.
Tips and tricks

Follow the green highlight, even when the face is not green.
- Focus on the highlight colour, not the sticker colour. Green means click; yellow means wait.
- Use the UNDO list at the top to see the next moves. CW means clockwise and CCW means counter-clockwise.
- Avoid repeated or random clicks. A wrong move adds another move to undo, but you can still recover.
- Try to match PAR, the number of original scramble moves. Level 1 starts with three moves; later levels increase the scramble up to eight moves and the selection speed increases.
- There is no countdown. Take your time to learn the rhythm, then try to improve your best time and turn count.
Play the game: One-Button Cube on MATLAB Central
In our dynamics and kinematics course we simulated robots in low gravity, and I wondered what astronauts would do for fun after work. My answer is Moon Kick: tap once to lock the angle, tap again to set the power, and send the ball floating past a robot goalkeeper. Instead of storing pictures, the game calculates its sky, kick and goalkeeper with a little trigonometry.Play Moon-Kick
functions, used and its role
The contest needs only three handles. Everything else is a helper that takes the game state and returns the new state.
function g = game()
g.init=@ini; g.update=@upd; g.render=@rnd;
end
Every other part, like the goal check and the effects, is a small helper that takes the game state and returns the new state.
Two taps, two sine waves
Angle and power swing back and forth on sine waves, and your tap freezes the value.
s.ang = 8 + 70*(.5 + .5*sin(3.2*u));
v = 390*s.pw; s.vx = v*cosd(s.ang);
s.vy = v*sind(s.ang);
The Moon is just a smaller number
Lowering gravity in the step update makes every kick fly about six times farther.
s.vy = s.vy - 117*d;

A galaxy from polar coordinates
Each star's angle grows with its distance from the centre, which makes a spiral. Squashing the vertical part tilts it, and adding to the angle each frame rotate it .
r = 120*rand(n,1).^.7; a = r/18 + randn(n,1)*.25;
x = 400 + r.*cos(a); y = 430 + .45*r.*sin(a);

Moon-Bot, the goalkeeper
Moon-Bot glides up and down on a sine wave with a random phase. The shot is decided when the ball reaches the goal line. I work out the ball's height on that line, so even a fast ball can't skip past him
yy = y + (640-x)/(s.bx-x)*(s.by-y);

In few words for you to enjoy the game you have to master th power and angles as follow:
Tricks to play
- Lock the angle between 30° and 45°. This gives a long arc that lands inside the goal. Below 25° the ball needs almost full power, and above 50° it drops short or goes over the bar.
- Use about 70% power. At 35° the safe power is 63% to 80%, and full power sends the ball over the bar.
- Watch Moon-Bot's rhythm before you kick. He moves up and down about once per second. A flatter kick (30°) reaches him sooner, so he has less time to get in the way.
Final word
Behind every floating kick in Moon Kick, there is nothing more than a few trigonometric functions. A sine wave sweeps the aim, cosine and sine turn your tap into a flying ball, and polar coordinates draw a whole galaxy. This is what I love about MATLAB: a few simple functions can become a game.
So the next time you tap to lock the angle, remember that you are playing with trigonometry. Try the tricks above, then change a number and see what happens. I hope you discover how much fun it can be.
Thanks for reading, and enjoy the joy of trigonometry! 🌙⚽
Informazioni su Discussions
Discussions is a user-focused forum for the conversations that happen outside of any particular product or project.
Get to know your peers while sharing all the tricks you've learned, ideas you've had, or even your latest vacation photos. Discussions is where MATLAB users connect!
Get to know your peers while sharing all the tricks you've learned, ideas you've had, or even your latest vacation photos. Discussions is where MATLAB users connect!
Altre aree comunitarie
MATLAB Answers
Poni e rispondi a domande su MATLAB e Simulink
Scambio di file
Scarica o contribuisci al codice inviato da un utente
Cody
Risolvi problemi, impara ad usare MATLAB e ottieni badge
Blog
Scopri MATLAB e Simulink dall’interno
Area giochi di chat AI
Utilizza l'intelligenza artificiale per generare la bozza iniziale del codice MATLAB e rispondere alle domande!
































