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

채택된 답변

Dave B
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
leonard_laney
leonard_laney 2021년 11월 14일
Thanks so much! If i wanted to pass an object by reference, would I have to redefine the whole class? Like say i wanted to redefine position using the moveTorpedo function, can I do that without making a copy of the torpedo?
Dave B
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 CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by