2011-11-19 82 views
0

我正在開發Windows手機遊戲,並且我在精靈機芯方面遇到困難。 當我只有一個快速觸摸和釋放時,我想要做的是讓精靈逐漸移動到屏幕上觸摸的位置。 現在我所能做的就是讓精靈立刻跳到觸摸位置,或者在觸摸按下時移動到觸摸位置。XNA Windows Phone 7雪碧機芯

代碼跳轉到觸摸的位置:在觸摸的狀態

TouchCollection touchCollection = TouchPanel.GetState(); 
     foreach (TouchLocation tl in touchCollection) 
     { 
      if ((tl.State == TouchLocationState.Pressed) 
       || (tl.State == TouchLocationState.Moved)) 
      { 
       Vector2 newPos = new Vector2(tl.Position.X,tl.Position.Y); 

        if (position != newPos) 
        { 
         while (position.X < newPos.X) 
         { 
          position.X += (float)theGameTime.ElapsedGameTime.Milliseconds/10.0f * spriteDirectionRight; 
         } 
        } 
      } 
     } 

代碼逐漸沿着移動:

TouchCollection touchCollection = TouchPanel.GetState(); 
     foreach (TouchLocation tl in touchCollection) 
     { 
      if ((tl.State == TouchLocationState.Pressed) 
       || (tl.State == TouchLocationState.Moved)) 
      { 
       Vector2 newPos = new Vector2(tl.Position.X,tl.Position.Y); 

        if (position != newPos) 
        { 

          position.X += (float)theGameTime.ElapsedGameTime.Milliseconds/10.0f * spriteDirectionRight; 

        } 
      } 
     } 

這些都是在Sprite類的Update()方法。

回答

0

這樣的事情...對不起,我沒有通過編譯器運行它,所以可能會有一些語法錯誤。聲明這些在類字段:

Vector2 newPos; 
bool moving = false; 

然後在更新方法:

 TouchCollection touchCollection = TouchPanel.GetState(); 
     foreach (TouchLocation tl in touchCollection) 
     { 
      if ((tl.State == TouchLocationState.Pressed) 
       || (tl.State == TouchLocationState.Moved) 
       || (tl.State == TouchLocationState.Released)) 
      { 
       newPos = new Vector2(tl.Position.X, tl.Position.Y); 
       moving = true; 
      } 
     } 
     if (moving && newPos != position) 
     { 
      Vector2 delta = newPos - position; 
      Vector2 norm = delta; 
      norm.Normalize(); 
      Vector2 distanceToMove = norm * ((float)gameTime.ElapsedGameTime.TotalMilliseconds * .5f); 
      if (distanceToMove.LengthSquared() > delta.LengthSquared()) 
      { 
       position = newPos; 
       moving = false; 
      } 
      else 
      { 
       position += distanceToMove; 
      } 
     } 
+0

「操作員‘*’不能應用於類型的操作數‘無效’和‘浮動’」它給我這個錯誤爲Vector2 distanceToMove = delta.Normalize()*(float)theGameTime.ElapsedGameTime.Milliseconds * 10f;「 –

+0

好吧抱歉我修復了它,忘了Normalize修改了現有的Vector2並且沒有返回一個。我去跑它,這一個已經過測試。 –

+0

這很好,謝謝。 –