Move bar in ponggame with arrowkeys
Show older comments
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
Answers (1)
Manas Meena
on 12 Feb 2021
0 votes
You might find the following file exchange links useful as references
Categories
Find more on Graphics Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!