Collision Problem (Square 2d)
    5 views (last 30 days)
  
       Show older comments
    
Hello there, i am trying to write some code that plots a square moving along a line with a certain velocity when the centre of the squares coordinates get within a certain tolerance the direction of the velocity becomes negative and so it 'bounces' off the wall. My code is below but the constraints in terms of direction don't seem to be working any insight would be greatly appreciated. Best Regards
fps = 20; 
dt = 1/fps; 
tmax = 10; 
t = 0; 
theta = 0;
dtheta = 1/20;
p = transpose([20,20,1]); 
v = transpose([50,25,1]); 
Vobj = transpose([2, -2, 1; 2,2,1; -2, 2, 1; -2, -2, 1]);
while t < tmax
    x = p + t*v;
    if x(1)<= 5 || x(1) >= 95
      v(1)=-v(1);
    elseif x(2)<= 5 || x(2) >= 95
      v(2)=-v(2);
    end
    p = x;
      % Transformations
      T = [1,0,p(1);0,1,p(2);0,0,1];
      S = [1+0.2*sin(2*t),0,0; 0,1+0.2*sin(2*t),0;0,0,1];
      R = [cos(theta),sin(theta),0 ;-sin(theta),cos(theta),0;0,0,1];
      % Application of Transformations
      V = R*S*T*Vobj;
      fill(V(1,:),V(2,:),'r')
      hold on
      axis([0,100,0,100])
      hold off
      shg;
      pause(0.3);
      % Updates
      t = t + dt;
      theta = theta + dtheta;
  end
1 Comment
  aliyah islam
 on 18 Dec 2019
				Did you end up figuring this problem out? If so have you still got the matlab code for it, as i have a similar problem to solve. Thanks 
Answers (1)
  madhan ravi
      
      
 on 2 Nov 2018
           fps = 20; 
      dt = 1/fps; 
      tmax = 10; 
      t = 0;
      x =[20,20,1]; 
      v = [50,25,1]; 
      ctr=1;
      while t < tmax
          p(ctr,:) = x + t*v;
          if p(1) < 5 || p(1) > 95 || p(2) < 5 || p(2) > 95
              p(ctr,:) = x + t*(-v);
          else
              p(ctr,:) = x + t*v;
          end
          plot(p(1),p(2),'o')
          hold on
          axis([0,100,0,100])
          hold off
          pause(1);  
          t = t + dt;
      end
3 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

