2011-09-26 57 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求救! –