Error : "Check for incorrect argument data type or missing argument in call to function 'spawnTorpedo'."
1 回表示 (過去 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!