Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

My professor wants a program where multiple pucks bounce off the walls of a plot

ID: 3621323 • Letter: M

Question

My professor wants a program where multiple pucks bounce off the walls of a plot and bounce off each other when they collide. So far the code I have has multiple pucks bouncing off the walls of the plot but not bouncing off each other when they collide. My professor wants us to use functions and make them as simple as possible. She says the function for collision should have this following form:
function out_acc = updateAcc(in_pos)
initialize the acceleration matrix
% by default, each puck simply has the constant acceleration due to gravity
for j = 1:n
for k = j+1:n
compute the distance between puck j and k
if the distance is less than some threshold,
then update the acceleration for pucks j and k with a force in the opposite direction
end
end

This is the code I have so far(with 2 functions in different scripts):
Bounds = [0 3 0 5];
set(gca,'XLim',[Bounds(1) Bounds(2)],'YLim',[Bounds(3) Bounds(4)],'Drawmode','fast','Visible','on');
cla
axis square
pos = rand(2,2);
vel = rand(2,2)*0.1;
ball = plot(pos(1,:),pos(2,:),'ko')
for i = 1:1000
pos = updatePos(pos, vel);
vel = boundCheck(pos ,vel, Bounds);
set(ball,'xdata',pos(1,:),'ydata',pos(2,:));
drawnow;
pause(.01)
axis(Bounds)
end

function posNew = updatePos(posOld, vel);
posNew = posOld + vel;

function velNew = boundCheck(pos, velOld, Bounds)
velNew = velOld;
for i = 1:length(pos)
if ((pos(1,i) > Bounds(2)) || (pos(1,i) < Bounds(1)))
velNew(1,i) = -velOld(1,i);
end
if ((pos(2,i) > Bounds(4)) || (pos(2,i) < Bounds(3)))
velNew(2,i) = -velOld(2,i);
end
end

Explanation / Answer

If you want the pucks to bounce off each other, you need to perform more collision detection every time a puck moves. You can use the Pythagorean theorem to find the distance between the moving puck and all the others, and any time that is less than twice the radius of a single puck, those two pucks will have a collision. From there, you can have them bounce away from each other. You can find the direction they'd need to start moving by subtracting the x and y values of the two colliding pucks. They each move in opposite directions, obviously.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote