Error : "Check for incorrect argument data type or missing argument in call to function 'spawnTorpedo'."
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Dave B
2021-11-14
编辑:Dave B
2021-11-14
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 个评论
Dave B
2021-11-14
编辑:Dave B
2021-11-14
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).
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!