Problem with if statement within a while loop
12 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
I'm trying to make a 3D golf simulator but for some reason, I can't get the programme to tell me when the ball is in the hole, the if statement just doesn't seem to be working. I'd be very thankful if anyone could spot what's wrong with my code.
hx=250.*rand(1)
hy=250.*rand(1)
hz=0;
hr=0.0;
while (vx0*tf)<(hx-hr)||(hx+hr)<(vx0*tf)||(vy0*tf)<(hy-hr)||(hy+hr)<(vy0*tf)
v0= input('What is the new velocity?');
theta= input('What is the new swivel angle?');
sigma= input('What is the new tilt angle?');
%asks the user to input new values of speed and angle
endx=sx(1,end);
endy=sy(1,end);
%defines the displacement up to this point
vx0= v0*cos(theta)*cos(sigma);
vy0= v0*cos(sigma)*sin(theta);
vz0= v0*sin(sigma);
%calculates the x,y and z components of the initial velocity
az= -9.807;
%acceleration due to gravity
tf=2*v0*sin(sigma)/(-az);
%calculates the amount of time(tf) it takes for the ball to reach the
%ground.
t= 0: 0.01 : tf;
%defines the time interval as being between zero and the time the golf ball
%reaches the ground.
sx= vx0*t+endx;
sy= vy0*t+endy;
sz= vz0*t + 0.5*az*t.^2;
%formulas respectively calculate the x,y and z components of the
%displacement.
if (hx+hr)<(vx0*tf)&&(vx0*tf)<(hx-hr)&&(hy+hr)<(vy0*tf)&&(vy0*tf)<(hy-hr)
disp('Great Success!')
break
end
plot3(sx,sy,sz,'r:','Linewidth',4); hold on end
2 个评论
James Tursa
2016-2-27
If any of your variables are vectors, the if-test is likely not doing what you expect. If that is the case, make sure you are doing scalar comparisons to get the expected result.
回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!