2011-09-26 63 views
1

過去幾周我一直在學習f#,並在某些方面遇到了一些麻煩。我正在嘗試將它與XNA一起使用,並正在編寫一個非常簡單的遊戲。在f中找不到方法或對象構造函數#

我有一個簡單的播放器類實現DrawableGameComponent,然後重寫它的方法Draw,Update和LoadContent。

type Player (game:Game) = 
     inherit DrawableGameComponent(game) 

     let game = game 
     let mutable position = new Vector2(float32(0), float32(0)) 
     let mutable direction = 1 
     let mutable speed = -0.1 
     let mutable sprite:Texture2D = null 

     override this.LoadContent() = 
      sprite <- game.Content.Load<Texture2D>("Sprite") 

     override this.Update gt= 
      if direction = -1 && this.Coliding then 
       this.Bounce 
      this.Jumping 
      base.Update(gt) 

     override this.Draw gt= 
      let spriteBatch = new SpriteBatch(game.GraphicsDevice) 
      spriteBatch.Begin() 
      spriteBatch.Draw(sprite, position, Color.White) 
      spriteBatch.End() 
      base.Draw(gt) 

等等....

主要的遊戲類,然後讓新玩家對象等

module Game= 

    type XnaGame() as this = 
     inherit Game() 

     do this.Content.RootDirectory <- "XnaGameContent" 
     let graphicsDeviceManager = new GraphicsDeviceManager(this) 

     let mutable player:Player = new Player(this) 
     let mutable spriteBatch : SpriteBatch = null 
     let mutable x = 0.f 
     let mutable y = 0.f 
     let mutable dx = 4.f 
     let mutable dy = 4.f 

     override game.Initialize() = 
      graphicsDeviceManager.GraphicsProfile <- GraphicsProfile.HiDef 
      graphicsDeviceManager.PreferredBackBufferWidth <- 640 
      graphicsDeviceManager.PreferredBackBufferHeight <- 480 
      graphicsDeviceManager.ApplyChanges() 
      spriteBatch <- new SpriteBatch(game.GraphicsDevice) 
      base.Initialize() 

     override game.LoadContent() = 
      player.LoadContent() //PROBLEM IS HERE!!! 
      this.Components.Add(player) 

     override game.Update gameTime = 
      player.Update gameTime 


     override game.Draw gameTime = 
      game.GraphicsDevice.Clear(Color.CornflowerBlue) 
      player.Draw gameTime 

編譯器會報告錯誤說「法或對象的構造LoadContent不發現「

我覺得這很奇怪,因爲繪製和更新都可以正常工作,並且可以通過intellisense找到,但不是LoadContent!

這可能只是我做出的一個非常愚蠢的錯誤,但如果有人發現問題,我會非常感激!

感謝

回答

3

DrawableGameComponent.LoadContent被保護 - 這樣你就無法訪問您的XnaGame類調​​用它。

我不清楚什麼意思是最終調用它,但顯然你不應該直接自己調用它。

+0

謝謝!這是完全合理的,謝謝你指出這一點!所以如果我只是將我的對象添加到遊戲組件,那麼它應該被自動調用?再次感謝! –

+0

@EwenCluley:我不知道,說實話 - 我懷疑是這樣,但我自己並沒有做過任何XNA工作。 –

2

這個錯誤肯定聽起來很混亂。您在Player類型的定義中覆蓋了LoadContent成員,但(如Jon指出的)成員爲protected。 F#不允許您使該成員更加可見,因此即使您的定義仍然爲protected(您通常無法在F#中定義protected成員,所以這就是錯誤消息較差的原因)。

您可以通過添加來自Player內來電LoadContent額外成員解決的問題:

override this.LoadContent() = 
    sprite <- game.Content.Load<Texture2D>("Sprite") 
member this.LoadContentPublic() = 
    this.LoadContent() 

...那麼LoadContent成員仍然會protected(從外面無法訪問),但新LoadContentPublic成員將會公開(這是F#中member的默認值),您應該可以從XnaGame中調用它。

但是,正如Jon指出的 - 也許你不應該自己調用方法,因爲XNA運行時會在需要時自動調用它。

+0

偉大,非常有用和深刻的答案。 thansk爲此它是有道理的 - 我接縫recal在c#我可以改變覆蓋的方法的可見性...我認爲...奇怪的是,f#不允許這樣做。 Thansk求救! –