[英]Make an object rotate and move towards a touch in 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)
這是一個非常簡單的例子:
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纏繞,而不是幾乎一直旋轉,如果發生這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.