rectangle command not working in a function with multiple variables in the coordinate argument
Show older comments
This has stumped me for a while now and it's very annoying.
this is my function, it uses the KeyPressFcn to move a rectangle up, down, left and right with the arrow keys:
figure('Color',[0.1 .6 0],'Name',...
'Highwayman','MenuBar','none','NumberTitle','off','Resize','off',...
'position',[500,100,400,800],'KeyPressFcn',@userkey);
axis([0,5,0,20])
set(gca,'color','black')
driverx = 2;
drivery = 1;
startingcar = rectangle('position',[driverx+.25 drivery .5 2],'EdgeColor','r','Curvature',[0.5,1],'FaceColor','red');
function userkey(src,event)
global driverx drivery redcar startingcar
k = event.Key;
%disp(event.Key)
switch k
case 'leftarrow'
driverx = driverx-1;
delete(redcar)
if driverx<0
driverx = 0;
end
redcar = rectangle('position',[driverx+.25 drivery .5 2],'EdgeColor','r','Curvature',[0.5,1],'FaceColor','red');
case 'rightarrow'
driverx = driverx+1;
delete(redcar)
if driverx>4
driverx = 4;
end
%rightturn = [driverx+.25 drivery .5 2];
redcar = rectangle('position',[driverx+.25 drivery .5 2],'EdgeColor','r','Curvature',[0.5,1],'FaceColor','red');
case 'uparrow'
drivery = drivery+2;
delete(redcar)
if driverx>18
driverx = 18;
end
redcar = rectangle('position',[driverx+.25 drivery .5 2],'EdgeColor','r','Curvature',[0.5,1],'FaceColor','red');
case 'downarrow'
drivery = drivery-2;
delete(redcar)
if driverx<1
driverx = 1;
end
redcar = rectangle('position',[driverx+.25 drivery .5 2],'EdgeColor','r','Curvature',[0.5,1],'FaceColor','red');
end
end
Whenever the user presses a key it should move the car in that direction, with if statements preventing it from leaving the border, and indeed when it is just left and right, where drivery is replaced with just the number 1 in the rectangle command, it works fine, but when I add the second dimension of up and down, it gives an error when I try to move in any direction:
Error using rectangle
Value must be a 4 element vector
Error in Highwayman>userkey (line 143)
redcar = rectangle('position',[driverx+.25 drivery .5 2],'EdgeColor','r','Curvature',[0.5,1],'FaceColor','red');
Error using Highwayman (line 103)
Error while evaluating Figure KeyPressFcn.
It's referring to [driverx+.25 drivery .5 2] because it works fine when it's just left and right: [driverx+.25 1 .5 2]. The value is definitely a 4 element vector, it looking like [2.25 1 0.5 2] if assigned to a variable and the variable put in its place but it returns the same error and doesn't move the rectangle for any input.
The rectangle function with two variables works fine outside that function and in the command window, it's just there where it doesn't work. Any help?
Accepted Answer
More Answers (0)
Categories
Find more on Graphics Object Properties 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!