2014-08-29 58 views
2

我正在開發一個在Kivy中觸摸的遊戲中獲取對象時遇到了一些問題。這是我到目前爲止的代碼:使對象旋轉並在Kivy中觸摸移動

class Player(Widget): 
angle = NumericProperty(0) 

def on_touch_move(self, touch): 
    y = (touch.y - self.center[1]) 
    x = (touch.x - self.center[0]) 
    calc = math.degrees(math.atan2(y, x)) 
    new_angle = calc if calc > 0 else 360+calc 

    self.angle = new_angle 
    self.pos = [touch.x - 50, touch.y - 50] 

我要的是,當用戶觸摸(並保持畫面),在「玩家」不斷旋轉,以匹配觸摸的位置,並逐步走向移動觸摸屏。建議? 我會繼續工作,讓你知道我使用什麼。

由於提前, Ilmiont

編輯: 發佈以來,我嘗試這樣做,它的效果要好得多......但對象停止從光標移動往往是幾個像素,到一邊。我希望它停止,所以光標應該直接在上面...即玩家在移動設備上的手指將握住它。

def on_touch_move(self, touch): 
    y = (touch.y - self.center[1]) 
    x = (touch.x - self.center[0]) 
    calc = math.degrees(math.atan2(y, x)) 
    new_angle = calc if calc > 0 else 360+calc 

    self.angle = new_angle 
    anim = Animation(x = touch.x, y = touch.y) 
    anim.start(self) 
+0

當你說「不斷旋轉以匹配觸摸的位置」時,你的意思是玩家旋轉以面對觸摸位置? 「持續」是什麼意思? – 2014-08-29 15:59:45

+0

是的,「旋轉以面對接觸的位置」。儘管如此,請參閱我的編輯,但這種作品不是但似乎相當不穩定和不準確。 – Ilmiont 2014-08-29 16:01:23

回答

1

這裏是一個非常簡單的例子:

from kivy.lang import Builder 
from kivy.base import runTouchApp 
from kivy.uix.image import Image 

from kivy.graphics import Rotate 
from kivy.properties import NumericProperty 

from math import atan2, degrees, abs 

from kivy.animation import Animation 

Builder.load_string('''                                   
<PlayerImage>:                                     
    canvas.before:                                    
     PushMatrix                                    
     Rotate:                                     
      angle: self.angle                                 
      axis: (0, 0, 1)                                  
      origin: self.center                                 
    canvas.after:                                    
     PopMatrix                                    
''') 

class PlayerImage(Image): 
    angle = NumericProperty(0) 

    def on_touch_down(self, touch): 
     Animation.cancel_all(self) 
     angle = degrees(atan2(touch.y - self.center_y, 
           touch.x - self.center_x)) 

     Animation(center=touch.pos, angle=angle).start(self) 


root = Builder.load_string('''                                 
Widget:                                       
    PlayerImage:                                    
     source: 'colours.png'                                 
     allow_stretch: True                                  
     keep_ratio: False                                  
''') 

runTouchApp(root) 

這不僅會非常基礎,但也許它可以幫助你回答你的問題。

你可能想要改變的一件大事是使用動畫有點不靈活。如果這是一種動態類型的遊戲,那麼這個任務對你的遊戲更新循環來說可能會更好,每次打勾都會遞增移動和旋轉。除此之外,這對於變化來說更加靈活,並且使得以恆定速率移動/旋轉更容易,而不是在這種情況下始終準確地取1。

當然還有其他一些小問題,比如將角度從-pi轉換爲pi,而不是幾乎全部旋轉,如果發生這種情況。