Python简单反弹物理

2024-05-13 14:57:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道,如果没有任何物理模块,Python可以直接实现物理模块。弹跳物理,我不是说引力,我是说更像最近发布的iOS游戏“好吗?”作者:Philipp Stollenmayer(https://appsto.re/us/1N7v5.i)。我知道,如果一个球碰到直边,它的速度是相反的。因此,根据这个图表: 当球碰到A和C时,它的X速度是相反的,当它击中B和D时,它的Y速度是相反的。但是如果我们的图表是这样的: 给定平台的角度,我怎么才能找到新的X和Y速度?另外,如何把X和Y的速度转换成度呢?在

我从维基百科上发现弹跳的对称线垂直于它撞击的表面。在

最后一个问题是,在pygame中,如何找到一条线的角度,并创建一条具有一定角度的线。在


Tags: 模块httpsre游戏图表物理引力作者
2条回答

reflectedVector = velocityVector - scale(surfaceNormal, 2.0*dot(surfaceNormal, velocityVector))

velocityVector是向表面移动的速度,用矢量表示。 surfaceNormal垂直于曲面,长度为1。在

dotdot productdot(v1, v2) = v1.x*v2.x + v1.y*v2.y

scale是矢量“缩放”运算。scale(inVec, scalar) = vector2d(inVec.x*scalar, inVec.y*scalar) `在

只有当速度指向表面时才反射速度,如果它正在移动,请不要

  1. 如果dot(surfaceNormal, velocity) < 0球正朝它移动。在
  2. 如果dot(surfaceNormal, velocity) == 0.0球与表面平行。在
  3. 如果dot(surfaceNormal, velocity) > 0.0球正在远离表面。在

下面是一些简单的技巧,很容易理解。我用了pygame。我们需要一些常数,如“帧速率”和像素位移[球]来可视化结果。我们要做的就是这样。一旦它撞到墙壁上,我们会根据墙的哪一面来改变像素的流向。[对我们来说,它看起来像是偏离了墙壁] 按照代码操作。在

    self.ball     = pygame.Rect(300,PADDLE_Y -  BALL_DIAMETER,BALL_DIAMETER,BALL_DIAMETER)
    self.ball_vel = [10,-10]
    self.ball.left += self.ball_vel[0] 
    self.ball.top  += self.ball_vel[1]
    if self.ball.left <= 0:                  # -1
        self.ball.left = 0
        self.ball_vel[0] = -self.ball_vel[0]
    elif self.ball.left >= MAX_BALL_X:       # -2
        self.ball.left = MAX_BALL_X
        self.ball_vel[0] = -self.ball_vel[0]

    if self.ball.top < 0:                    # -3
        self.ball.top = 0
        self.ball_vel[1] = -self.ball_vel[1]
    elif self.ball.top >= MAX_BALL_Y:        # 4         
        self.ball.top = MAX_BALL_Y 
        self.ball_vel[1] = -self.ball_vel[1]
    # If the ball hits the left wall it has to invert its velocity [Moving left     become right]   -1  
    # If the ball hits the Right wall it has to invert its velocity [Moving right become left]  -2    
    # If the ball hits the Bottom wall it has to invert its velocity [Moving downwards become upwards]  -3        
    # If the ball hits the Right wall it has to invert its velocity [Moving upwards become downwards]  -4                

相关问题 更多 >