Move bar in ponggame with arrowkeys

조회 수: 1 (최근 30일)
Ilse van der Veen
Ilse van der Veen 2021년 2월 9일
답변: Manas Meena 2021년 2월 12일
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

답변 (1개)

Manas Meena
Manas Meena 2021년 2월 12일

카테고리

Help CenterFile Exchange에서 Migrate GUIDE Apps에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by