Skip to content

Instantly share code, notes, and snippets.

@Doggie52
Last active March 26, 2016 21:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Doggie52/b556e19cd1c7ca1b9272 to your computer and use it in GitHub Desktop.
Save Doggie52/b556e19cd1c7ca1b9272 to your computer and use it in GitHub Desktop.
A simple example of how to plot BOIDs or other agents on a plot in MATLAB
function Plot = draw( Plot )
% Author: Douglas Stridsberg <d@stridsberg.uk>
%
% INFO
% Redraws the plot, one BOID at a time.
% Intended to be run once every frame. The Plot object requires
% - an array of handles to old BOIDs created;
% - an array of BOID objects. These, in turn, require
% - position vectors.
%
% INPUT PARAMETERS
% Plot - an object consisting of the following properties:
% - Boids: array of your boids (see the code for hints on what they should contain)
% - Plot_Handles: array of figure handles
%
% How you choose to implement this is up to you. This is not a working prototype per se, it is more a proof of concept.
% Look at what's been done and take away what you need for your project to work, is my suggestion!
% Clear current plot of old BOIDs
for i = 1:length( Plot.Plot_Handles )
if Plot.Plot_Handles(i) ~= 0 % we don't want to delete the root object!
delete( Plot.Plot_Handles(i) );
end
end
Plot.Plot_Handles = [ ];
% Read BOID icon
[ img_boid, ~, alpha_boid ] = imread('gfx/icon_boid.png');
% Resize BOID icon
scale = 1.0;
img_boid = imresize( img_boid, scale, 'lanczos3' );
alpha_boid = imresize( alpha_boid, scale, 'lanczos3' );
% Finds all BOIDs' positions
for i = 1:length( Plot.Boids )
% Reference a particular BOID
Boid = Plot.Boids{i};
% (OPTIONAL) Rotate the icon if you need this
angle = -1 * get_vector_angle( Boid.Velocity_n ) - 90; % imrotate rotates ccw
img_i = imrotate( img_craft, angle );
alpha_i = imrotate( alpha_craft, angle );
% Plot the image onto the figure
%
% My icon size was 30x30 pixels, so my icon is on the middle of
% the BOID at coordinates -15, -15
Plot.Plot_Handles(i) = image( Boid.Position(1)-15, Boid.Position(2)-15, img_i );
% Set alpha data to enable transparency
set( Plot.Plot_Handles(i), 'AlphaData', alpha_i );
end
% Redraw plot
drawnow;
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment