Error : "Check for incorrect argument data type or missing argument in call to function 'spawnTorpedo'."
1 view (last 30 days)
Show older comments
I'm trying to create a simple class for a game project I'm doing for school. Torpedo is just an object that has a position and a direction that it's facing. If I try to test the functions (ie. t = spawnTorpedo(2,3,4,5) I get the error "Check for incorrect argument data type or missing argument in call to function 'spawnTorpedo'." Any help would be appreciated.
classdef torpedo
properties
x
y
xdir
ydir
end
methods
function torp = spawnTorpedo(xStart,yStart,cursorX,cursorY)
dir = [cursorX - xStart, cursorY - yStart];
dir = dir/norm(dir);
torp.x = xStart;
torp.y = yStart;
torp.xdir = dir(1);
torp.ydir = dir(2);
end
function objOut = moveTorpedo(objIn,speed)
objOut.x = objIn.x + objIn.xdir*speed;
objOut.y = objIn.x + objIn.ydir*speed;
end
end
end
0 Comments
Accepted Answer
Dave B
on 14 Nov 2021
Edited: Dave B
on 14 Nov 2021
spawnTorpedo is a (non-static, non-constructor) method, so the first argument should be the object:
obj = torpedo;
obj.spawnTorpedo(2,3,4,5)
(Alternatively, with MATLAB objects, you can use a function like syntax)
spawnTorpedo(obj,2,3,4,5)
And the signature should be:
function torp = spawnTorpedo(torp,xStart,yStart,cursorX,cursorY)
Unless it's the constructor (which was maybe the intent), in which case the signature should be:
function torp = torpedo(xStart,yStart,cursorX,cursorY)
and you should call it as:
thistorp = torpedo(2,3,4,5)
2 Comments
Dave B
on 14 Nov 2021
Edited: Dave B
on 14 Nov 2021
MATLAB has a pretty different approach to how you do this than other languages.
If you define your class as a handle class (this means subclass from handle):
classdef torpedo < handle
Then objects of the class are always treated as references:
a=torpedo; % ignoring your constructor arguments
a.x=1;
b=a;
b.x=2;
a.x %will be 2, a and b both point to the same instance
If you make torpedo a handle class, then your move function will look like:
function moveTorpedo(obj, speed)
obj.x = obj.x + objIn.xdir*speed;
obj.y = obj.y + objIn.ydir*speed; %note I fixed a typo here where you had an x but I suspect wanted a y!
end
Then you can just do:
torp1=torpedo;
torp.moveTorpedo(10);
If your class isn't a handle class, then you have to create a copy when you move it (although it's certainly possible that there will be an optimization under the hood that prevents this from being expensive).
More Answers (0)
See Also
Categories
Find more on Construct and Work with Object Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!