我一直在努力解决这个问题。下面是 kivy 应用程序早期阶段的 python/kivy 代码。问题在于球员的运动。Kivy 过度补偿了 dx 和 dy 运动,导致玩家运动不断抖动。我不知道如何解决这个问题。有任何想法吗?
注意:这段代码的大部分内容是不完整的,但玩家的移动大部分已经完成。运动问题发生在 " Player
" 类中。
编辑:这是我按照以下帖子的建议尝试的
import kivy
kivy.require('1.1.1')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty, ListProperty, NumericProperty
import math
from kivy.clock import Clock
import time
import random
PLAYER_SPEED = 10
ENEMY_SPAWN = 3
UPDATE_SPEED = .01
MIN_INITIAL_PLAYER_MINION_DISTANCE = 200
class Player(Widget):
velocity_x = NumericProperty(0)
velocity_y = NumericProperty(0)
target = ListProperty([])
speed = NumericProperty(PLAYER_SPEED)
def __init__(self, **kwargs):
Widget.__init__(self)
self.target = [399.0, 399.0]
def update_target(self, new_target):
self.target = new_target
def move(self):
dx = self.target[0] - self.center[0]
dy = self.target[1] - self.center[1]
x_1 = self.pos[0] - self.center[0]
y_1 = self.pos[1] - self.center[1]
total = math.sqrt(dx ** 2 + dy**2)
self.velocity_x = (dx / total) * self.speed
self.velocity_y = (dy / total) * self.speed
if math.sqrt(x_1** 2 + y_1**2) < self.speed:
self.pos = self.center
else:
new_x = self.pos[0] + self.velocity_x
new_y = self.pos[1] + self.velocity_y
self.pos = (new_x,new_y)
class Enemy(Player):
velocity_y = NumericProperty(PLAYER_SPEED)
def __init__(self, **kwargs):
Widget.__init__(self)
self.center = kwargs.get('start_pos',[0,0])
def move(self):
self.pos = (self.pos[0], self.pos[1] + self.velocity_y)
def distance(widget1, widget2):
dist = math.sqrt((widget1.pos[0]-widget2.pos[0])**2 + \
(widget1.pos[1]-widget2.pos[1])**2)
return dist
class Game(Widget):
player1 = ObjectProperty(None)
enemies = ListProperty([])
decoys = ListProperty([])
def setup(self):
self.enemies = []
self.decoys = []
self.player1.center = self.center
self.setup_schedules()
#Don't forget about good code organization!
def setup_schedules(self):
Clock.schedule_interval(self.update, UPDATE_SPEED)
Clock.schedule_interval(self.spawn_enemy, ENEMY_SPAWN)
def update(self,dt):
self.player1.move()
def spawn_enemy(self, dt):
x = float(random.randint(0, self.width))
y = float(random.randint(0, self.height))
enemy = Enemy(start_pos = (x,y))
while distance(enemy, self.player1)< MIN_INITIAL_PLAYER_MINION_DISTANCE:
x = float(random.randint(0, self.width))
y = float(random.randint(0, self.height))
enemy.pos = (x,y)
self.enemies.append(enemy)
self.add_widget(enemy)
def score(self):
zero_score = time.time()
player_score = zero_score + 1
#on_touch_move vs on_touch_down
def on_touch_move(self, touch):
self.player1.update_target([touch.x, touch.y])
#Entry Point into app
class GameApp(App):
def build(self):
game = Game()
game.setup()
return game
def main():
GameApp().run()
main()