how to make a simple jump game in matlab

Here's a simple example of a MATLAB code for a jump game:

main.m
clc; 
close all;
clear all;
set(0,'DefaultFigureWindowStyle','docked')

% Initializations
hFig = figure(1);
set(hFig, 'Position', [0 0 800 600])
axis([0 100 0 100])
hold on
x_pos = 10;
y_pos = 10;
hBlock = rectangle('Position',[x_pos y_pos 10 10],'FaceColor',[1 0 0]);
jumping = false;


while true
    % Detect key press
    c = get(hFig, 'CurrentCharacter');
    if(strcmp(c, ' '))
        jumping = true;
        t = 0:0.1:1;
        for i = 1:length(t)
            y_pos = 10 + 20*t(i) - 100*t(i).^2;
            set(hBlock, 'Position',[x_pos y_pos 10 10]);
            pause(0.01);
        end
        jumping = false;
    end
    
    if(~jumping)
        % Move the character
        x_pos = x_pos + 1;
        set(hBlock, 'Position',[x_pos y_pos 10 10]);
        pause(0.01);
    end
end
796 chars
38 lines

This code initializes a figure window and a rectangle that represents the character. The game loop moves the character to the right and detects the space bar key press to initiate a jump using a quadratic function. The animation pauses briefly each loop, which controls the speed of the game. You can modify the values of the parameters to achieve desired results.

related categories

gistlibby LogSnag