我动画中的小错误

时间:2017-01-29 23:32:06

标签: matlab

%Re-setting the MatLab enviroment
close all;
clear all;
clc;
%The box to contain the ball
X = [0 0 5 5 0];
Y = [0 5 5 0 0];
%Declaring the balls initial conditions
initpos.x = rand()*5;
initpos.y = rand()*5;
if 2*initpos.x == initpos.y;
initpos.x = initpos.x + dt;
end
R_Ball = 0.1;
F_Co_eff = 0.85;
initvel = 0.35;
%Conditions to spawn the ball in our box
if initpos.y > 4.9
initpos.y = initpos.y - R_Ball;  
end
if initpos.y < 0.1
initpos.y = initpos.y + R_Ball;  
end
if initpos.x < 0.1
initpos.x = initpos.x + R_Ball;  
end
if initpos.x > 4.9
initpos.x = initpos.x - R_Ball;  
end
%Animation timestep
dt = 0.00125;
%Executing the animation
pos.xy = [initpos.x ; initpos.y];
vel = [initvel ; initvel];
Movement = [1 ; 2].*dt; % Vector to iterate and change the position of the    ball,
%Drawing the first frame
plot(X,Y,'k');
rectangle('position',[initpos.x initpos.y R_Ball R_Ball],'Curvature',[1     1],'FaceColor','b');

while 1
%Updating the ball's position
vel(1) = vel(1) - Movement(1);
vel(2) = vel(2) - Movement(2);
pos.xy(1) = pos.xy(1) + vel(1);
pos.xy(2) = pos.xy(2) + vel(2);
%Maintaining the ball within the axis by changing direction by 90 degrees
%when an axis is hit
if pos.xy(1) > 5 - R_Ball;
vel(1)= (-1)*vel(1);
vel = (F_Co_eff)*vel;
end
if pos.xy(1) < 0 
vel(1)= (-1)*vel(1);
vel = (F_Co_eff)*vel;
end
if pos.xy(2) > 5 - R_Ball;
vel(2)= (-1)*vel(2);
vel = (F_Co_eff)*vel;
end
if pos.xy(2) < 0  
vel(2) = (-1)*vel(2);
vel = (F_Co_eff)*vel;
end

%Clearing the figure
clf;
%Drawing the frame
plot(X,Y,'k');
rectangle('position', [pos.xy(1) pos.xy(2) R_Ball R_Ball],'Curvature',[1 1],'FaceColor', 'b');
%Setting axis
axis([0 5 0 5]);
axis('equal');   
%Refresh rate
pause(dt)
end

想知道为什么我的程序出现问题我不明白为什么球会倾向于原点以及为什么它有时会在轴外产生。我有点新意,所以如果你能引用那些有问题的代码,我会很感激。

1 个答案:

答案 0 :(得分:1)

当你的球第一次离开框架时,你会镜像并阻尼速度,但下一个位置更新仍然可以超出框架。因此,你将永远地反映速度,球将永远不会重新进入。尝试在速度的符号上添加条件,即你要走的方向,如:

if vel(1) > 0 && pos.xy(1) > 5 - R_Ball;
vel(1)= (-1)*vel(1);
vel = (F_Co_eff)*vel;
end
if vel(1) < 0 && pos.xy(1) < 0 
vel(1)= (-1)*vel(1);
vel = (F_Co_eff)*vel;
end
if vel(2) > 0 && pos.xy(2) > 5 - R_Ball;
vel(2)= (-1)*vel(2);
vel = (F_Co_eff)*vel;
end
if vel(2) < 0 && pos.xy(2) < 0  
vel(2) = (-1)*vel(2);
vel = (F_Co_eff)*vel;
end

关于引力,看起来它是原点,因为你有一个倾斜的重力矢量,尝试一个垂直的矢量:

Movement = [0 ; 2].*dt;

对我而言,这条路似乎很自然并且在界限内:

enter image description here