collision code in Matlab
Afficher commentaires plus anciens
I'm coding this particle simulator in which the user can type in the width and height of the window, radius of the ball, number of balls, and also the starting coordinate of each ball. (Initial speed is random). Unfortunately i'm having trouble figuring out a method that i can use to determine if 2 or more balls collide. I'd really appreciate some pointers and some hints on getting this to work.
The whole program has many functions. This is just function that controls how each ball bounces. Currently it only has code to determine the ball's trajectory if it hits the wall.
function bounce = bounceFunc3(obj, addx,addy,x,y, w, h, rad)
%obj is the name of the ball. obj(1) is the first ball, obj(2) is the second, etc
%addx and addy determines the movement of the ball
%x & y is the current coordinate of the ball's center.
%w and h is the width and height
%rad is the radius of the ball
n = numel(obj); %Number of balls
while all((x >=0 & x <= w) & (y >= 0 & y <= h)) %while x and y positions of the balls are within the window
for k = 1:n %runs according to how many balls are present
%Bouncing on the sides of the wall
[x(k) y(k)] = getCenter(obj(k));
if y(k) >= h - rad %If the y position is at the top edge which is (Height - Radius of ball)
addy(k) = -addy(k)
end
if y(k) <= rad
addy(k) = -addy(k) %If the y position is at the bottom edge which is (Radius of ball)
end
if x(k) >= w - rad %If the x position is at the right edge which is (Width - Radius of ball)
addx(k) = -addx(k)
end
if x(k) <= rad %If the x position is at the left edge which is (Radius of ball)
addx(k) = -addx(k)
end
%Updates positions of the kth ball
xMove(obj(k),addx(k))
yMove(obj(k),addy(k))
%CODE TO DETERMINE COLLISION AND BOUNCE
end
redraw %Runs redraw function to graphically update position of the balls
end
end
Réponses (1)
Jan
le 20 Nov 2018
You know how to check the distance betwee the walls of the box and the center of the objects already. Now you need only to check the distances between the objects in addition:
%CODE TO DETERMINE COLLISION AND BOUNCE
for k2 = 1:n
if k ~= k2
dist = ... Distance between object k and object k2
if dist < 2 * rad
Collision
end
end
end
1 commentaire
Catégories
En savoir plus sur View and Analyze Simulation Results dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!