2014-08-29 62 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,而不是几乎全部旋转,如果发生这种情况。