Im trying to create an air hockey game in which both of the blockers are player controlled.

37 次查看(过去 30 天)
Im trying to figure out how to allow for simultaneous movement of the blocker patches in the figure as I want player 1 to be controlled by wasd and player 2 to be controlled by ijkl, however when trying to do so I can only move on at a time because they keep overwriting eachother.

回答(1 个)

Voss
Voss 2024-4-2,19:49
It should be feasible. Refer to the following code for one way you can control two different objects via a single key press function:
function air_hockey()
% create figure
f = figure('Name','Air Hockey','Menubar','none','Toolbar','none','IntegerHandle','off');
% create axes
ax = axes(f,'Box','on','XLim',[-1 1],'YLim',[-1 1],'XTick',[],'YTick',[]);
% puck
puck = line(ax,0,0,'Marker','.','MarkerSize',20,'Color','k');
% player 1 and 2 paddles
paddle = [ ...
line(ax,0,0.75,'Marker','s','MarkerSize',10,'Color','b','MarkerFaceColor','b') ...
line(ax,0,-0.75,'Marker','s','MarkerSize',10,'Color','r','MarkerFaceColor','r') ...
];
% how much to move the paddle on each key press
increment = 0.1;
% key press function
f.WindowKeyPressFcn = @kpf;
function kpf(~,evt)
if ~isempty(evt.Modifier)
% modifier (ctrl, shift, etc.) pressed/held; do nothing
return
end
% determine which player's paddle will move
[ism,idx] = ismember(evt.Key,'wasd');
if ism
% some player 1 key pressed
p_idx = 1;
else
[ism,idx] = ismember(evt.Key,'ijkl');
if ism
% some player 2 key pressed
p_idx = 2;
else
% some other key pressed; do nothing
return
end
end
% current position of the paddle
xd = get(paddle(p_idx),'XData');
yd = get(paddle(p_idx),'YData');
% dx and dy increments for each direction
% (up, left, down, right - same order as 'wasd' and 'ijkl' above)
dxy = [0 1; -1 0; 0 -1; 1 0]*increment;
% move the paddle
set(paddle(p_idx),'XData',xd+dxy(idx,1),'YData',yd+dxy(idx,2));
end
end

类别

Help CenterFile Exchange 中查找有关 Graphics Object Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by