Move bar in ponggame with arrowkeys

1 vue (au cours des 30 derniers jours)
Ilse van der Veen
Ilse van der Veen le 9 Fév 2021
For a schoolproject I am programming a pong ball game. I want to move the bar using the arrowkeys on my keyboard, but can only find a global function that works. But I actually want to avoid using global functions. Does someone have an alternative for me?
clear, clc, clf, clear all;
% ----------------------------- Lay out ----------------------------------%
Background = figure('color', [.2 .3 .8], 'KeyPressFcn', @keyboardFunction);
xaxis = [0 100];
yaxis = [-5 100];
GameField = axes('color', 'black', 'xlim', [xaxis(1) xaxis(2)],...
'ylim', [yaxis(1) yaxis(2)], 'xticklabels', [], ...
'yticklabels', []) %How to put axis off?
PosBall =[20 40] %Initial position ball
VelBall =[1 1] %Initial direction ball
Ball = line(PosBall(1),PosBall(2),'Marker', 'o', 'MarkerSize',...
10, 'MarkerFaceColor', 'white','MarkerEdgeColor','white') %Actual ball
global CenterBar = 45;
Bar = line([CenterBar - 5, CenterBar + 5], [0 0], 'LineWidth', 4, 'Color', 'b')
% -------------------------Control ball-----------------------------------%
tic;
while toc <20
if PosBall(1) < xaxis(1) || PosBall(1) > xaxis(2)
VelBall(1) = - VelBall(1);
end
if PosBall(2) > yaxis(2)
VelBall(2) = -VelBall(2);
end
if PosBall(2) < yaxis(1)
if abs(PosBall(1) - CenterBar) < 5
VelBall(2) = -VelBall(2);
else
disp("You lost the game!")
close all;return;
end
end
PosBall = PosBall + VelBall;
set(Ball, 'Xdata', PosBall(1), 'Ydata', PosBall(2));
set(Bar, 'Xdata', [CenterBar - 5, CenterBar + 5])
pause(.02);
end
function keyboardFunction(figure, event)
global CenterBar
switch event.Key
case 'leftarrow'
CenterBar = CenterBar - 2;
case 'rightarrow'
CenterBar = CenterBar + 2;
end
end

Réponses (1)

Manas Meena
Manas Meena le 12 Fév 2021

Catégories

En savoir plus sur Migrate GUIDE Apps dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by