【问题标题】:Why is my pygame ball not accelerating when using classes?为什么我的 pygame 球在使用类时没有加速?
【发布时间】:2017-08-04 15:57:10
【问题描述】:

所以我是 pygame/python/coding 的新手,也是第一次使用类。我已经制作了一个球在重力作用下弹跳并加速的工作 pygame 程序。但是,现在我使用类,球似乎只是以恒定的速度移动。请告诉我我做错了什么以及如何 我应该更改我的代码。提前致谢!

import pygame, sys


pygame.init()

red = (255,0,0)
black = (0,0,0)
white = (255,255,255)
blue = (0,0,255)

pygame.mouse.set_visible(0)
clock = pygame.time.Clock()

displaySize = (800,600)

screen = pygame.display.set_mode(displaySize)

g = 30
dt = 0.05

class ball:
    def __init__(self, x, y, vx, vy, r,ax,ay, color):

        dt = 0.05

        Cd = 0.01
        m = 5

        self.ay = ay
        self.ax = ax

        self.x = x
        self.y = y
        self.r = r
        self.color = color

        self.vx = vx
        self.vy = vx

def update(self, x, y):


    x, y = physics()
    pygame.draw.circle(screen, self.color, (int(round(x)),int(round(y))), self.r)
    pygame.display.update()

    def physics(self):


        self.Dy = Cd*self.vy*abs(self.vy)
        self.Dx = Cd*self.vx*abs(self.vx)

        self.Fy = self.m*g - self.Dy
        self.Fx = -self.Dx

        self.ay = self.Fy/m
        self.ax = self.Fx/m

        self.vy += self.ay*dt
        self.vx += self.ax*dt

        self.x +=self.vx*dt
        self.y +=self.vy*dt

        return self.x, self.y

one = ball(100,100,0,0,0,0,30,red)

while 1:
    clock.tick(30)
    screen.fill(blue)
    one.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

【问题讨论】:

标签: python python-2.7 pygame


【解决方案1】:

self.vx 和 self.vy 应该在构造方法中而不是在物理方法中,否则每次在游戏循环中调用物理方法时它们的值将被设置回 50 和 0,从而导致速度恒定.

【讨论】:

  • 好的,我明白你的意思了。只是在构造函数中添加 self.vx 和 self.vy 并没有解决问题,所以我尝试向其中添加更多内容。我把上面的代码改成了我现在认为的样子。你现在有什么办法让它工作吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多