2011-04-22 59 views
0

世界的Matlab嚮導。 6年的Matlab用戶,剛剛開始在Matlab中使用OOP玩遊戲。 我試圖使用一個方法作爲位於構造函數中的計時器的回調,它不起作用。我錯過了什麼? 請賜教。回調,定時器和OOP方法:幫助使用方法作爲定時器回調

感謝


classdef Vehicle 
% Vehicle 
% Vehicle superclass 

properties 
    Speed    % [Km/Hour] 
    Length   % [Meter] 
    Width    % [Meter] 
    Driver   % Properties of the driver 
    Current_Route  % Current route 
    Route_Percent  % Which Percent of the route the vehicle is in 
    Route_Direction % Driving forward or backeard on the routhe 
    Last_Action_Time % The time stamp for the last action of the vehicle 
end 

methods 
    function this = Vehicle(varargin) 
     this.Speed   = varargin{1}; % The speed of the car 
     this.Current_Route = varargin{2}; % What route the vehicle is on 
     this.Route_Percent = varargin{3}; % Where on the routeh is the vehicle 
     this.Route_Direction = varargin{4}; % To what direction is the car moving on the route 
     this.Last_Action_Time = clock;  % Set the time the thisect was creted 
     Progress_Timer = timer('TimerFcn', @Progress, 'Period', varargin{4}, 'ExecutionMode' ,'FixedRate'); % Sets a timer for progressing vehicle position 
     start(Progress_Timer) % Starts the timer 
    end 

    function this = Progress(this) 
     if (this.Route_Percent >= 0 && this.Route_Percent <= 100) % If the vehicle does not exceed the route map 
      this.Route_Percent = this.Route_Percent + ... 
       this.Route_Direction * this.Speed * etime(clock,this.Last_Action_Time)/3600/this.Current_Route.Length * 100 
      this.Last_Action_Time = clock; % Set the time the progress was done 
     else 
      this.delete;   % Vehicle is no longer relevant 
      stop(Progress_Timer); % Stops the timer 
     end 
    end 
end 
end 

回答

1

方法是不一樣的子功能。這意味着你想將對象傳遞給定時器功能。

Progress_Timer = timer('TimerFcn',@()Progress(this)) 

而且,你要vehicle成爲一個手柄類,因此它this在功能手柄每當對象被更新得到更新。

但是,您可以改爲使用set-methods來更新車輛的狀態,而不必使用其中一個屬性更改。這將更加透明。