我是一名 C 程序员,但想在 python 中对我的一些项目进行原型设计,到目前为止还可以,但我遇到了一个可能很简单的问题:当我在主模块一切正常,所以我认为我使用 self 或迭代有问题。
CBallSpawner:
from CBullet import Bullet
class BulletSpawner:
def __init__(self, count, position, color, radius, speed):
self.bull = []
self.cnt = count
self.speed = speed
self.freeze = False
self.acc = 0
self.position = position
self.createBullets(color, radius)
def createBullets(self, color, radius):
for i in range(1, self.cnt + 1):
self.bull.append(Bullet(radius, 0, color, i*(360.0/self.cnt), self.speed, self.position))
def speedUp(self, delta):
self.acc += delta
if self.acc > 1000 and not self.freeze:
self.speed += 0.1
for b in self.bull:
b.speed = self.speed
self.acc = 0
def tick(self, delta, w, h, window):
self.speedUp(delta)
for e in self.bull:
e.tick(delta, w, h)
def draw(self, window):
for c in self.bull:
window.draw(c.bullet_object)
对象已创建,但仍停留在其初始位置。当我调试公牛对象的位置时,它没有改变。如果 delta 足够高,子弹似乎会随机移动。
我主要打电话给
spawner = BulletSpawner(10, sf.Vector2(w/2, h/2), sf.Color.WHITE, 5, 0.16)
spawner.tick(delta, w, h, window)
spawner.draw(window)
Bullet 类和完全相同的迭代在主模块中运行良好,但由于我将其外包给 BulletSpawner 类,子弹将不再正常移动。感谢建议 E:Bullet 的重要部分,它们可以完美地独立运行
class Bullet:
def __init__(self, radius, outline, color, phi, speed, position):
self.phi = 0
self.speed = speed
self.bullet_object = sf.CircleShape()
self.position = sf.Vector2()
self.bounding_pos = sf.Vector2()
self.motion = sf.Vector2()
self.bounding = sf.Rectangle()
self.bullet_object.outline_thickness = outline
self.bullet_object.fill_color = color
self.bullet_object.origin = (radius, radius)
self.bullet_object.radius = radius
self.bounding.size = sf.Vector2(radius*2,radius*2)
self.bounding.position = self.position - (self.bounding.size/2)
self.position = position
self.phi = phi
self.calulateMotion()
def calulateMotion(self):
self.motion.x = math.cos(self.phi * (math.pi / 180))
self.motion.y = math.sin(self.phi * (math.pi / 180))
def tick(self, delta, w, h):
tmp = sf.Vector2(0, 0)
tmp.x = self.position.x + (self.motion.x * (self.speed * delta))
tmp.y = self.position.y + (self.motion.y * (self.speed * delta))
if tmp.x < 0 or tmp.x > w:
self.motion.x = -self.motion.x
self.bullet_object.fill_color = sf.Color(random.randint(0,255),random.randint(0,255),random.randint(0,255))
if tmp.y < 0 or tmp.y > h:
self.motion.y = -self.motion.y
self.bullet_object.fill_color = sf.Color(random.randint(0,255),random.randint(0,255),random.randint(0,255))
self.position.x += self.motion.x * (self.speed * delta)
self.position.y += self.motion.y * (self.speed * delta)
self.bullet_object.position = self.position
self.bounding.position = self.position - (self.bounding.size/2)
编辑:如果我只用 1 个 Bullet 创建一个生成器对象,那就够有趣了:
spawner = BulletSpawner(1, sf.Vector2(w/2, h/2), sf.Color.WHITE, 5, 0.16)
子弹正确移动