Python 2d球碰撞

2024-09-30 04:35:01 发布

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

以下是我收集到的:

from graphics import *
from random import *
from math import *

class Ball(Circle): def init(self, win_width, win_high, point, r, vel1, vel2): Circle.init(self, point, r)

    self.width = win_width
    self.high = win_high

    self.vecti1 = vel1
    self.vecti2 = vel2


def collide_wall(self):
    bound1 = self.getP1()
    bound2 = self.getP2()

    if (bound2.y >= self.width):            
        self.vecti2 = -self.vecti2
        self.move(0, -1)
    if (bound2.x >= self.high):
        self.vecti1 = -self.vecti1
        self.move(-1, 0)
    if (bound1.x <= 0):
        self.vecti1 = -self.vecti1
        self.move(1, 0)
    if (bound2.y <= 0):            
        self.vecti2 = -self.vecti2
        self.move(0, 1)

def ball_collision(self, cir2):
    radius = self.getRadius()
    radius2 = cir2.getRadius()

    bound1 = self.getP1()      
    bound3 = cir2.getP1()


    center1 = Point(radius + bound1.x,radius + bound1.y)
    center2 = Point(radius2 + bound3.x,radius2 + bound3.y)

    centerx = center2.getX() - center1.getX()
    centery = center2.getY() - center1.getY()

    distance = sqrt((centerx * centerx) + (centery * centery))

    if (distance <= (radius + radius2)):
        xdistance = abs(center1.getX() - center2.getX())
        ydistance = abs(center1.getY() - center2.getY())

        if (xdistance <= ydistance):
            if ((self.vecti2 > 0 & bound1.y < bound3.y) | (self.vecti2 < 0 & bound1.y > bound3.y)):
                self.vecti2 = -self.vecti2


            if ((cir2.vecti2 > 0 & bound3.y < bound1.y) | (cir2.vecti2 < 0 & bound3.y > bound1.y)):
                cir2.vecti2 = -cir2.vecti2



        elif (xdistance > ydistance):
            if ((self.vecti1 > 0 & bound1.x < bound3.x) | (self.vecti1 < 0 & bound1.x > bound3.x)):
                self.vecti1 = -self.vecti1

            if ((cir2.vecti1 > 0 & bound3.x < bound1.x) | (cir2.vecti1 < 0 & bound3.x > bound1.x)):
                cir2.vecti1 = -cir2.vecti1

def main(): win=GraphWin(“球形屏幕保护程序”,700700)

^{pr2}$

主()

好吧,问题就在这里。这个数学运算一点也不正确。有时它完美地工作有时一个球压倒另一个球,或者他们的反应不像一个球碰撞应该。我绞尽脑汁想找出问题出在哪里,但我觉得我离这个项目太近了,看不到它。任何帮助都将不胜感激。在


Tags: selfmoveifdefwidthwinhighcenter1
1条回答
网友
1楼 · 发布于 2024-09-30 04:35:01

修正你的“如果”陈述是合法和直截了当的。我想你可能想说下面的话。这很难说,因为你还没有记录你的代码。在

if cir2.vecti2 > 0 and bound3.y > bound1.y:
    cir2.vecti2 = -cir2.vecti2

请注意,bound3没有值。我相信你会发现其他问题的。在

我建议您备份并尝试增量编码。首先,试着让一个球合法地移动,从墙上弹下来。为该位置放入tracing print语句,并对其进行标记,以便您知道自己在代码中的位置。在

一旦你成功了,再加上第二个球。继续打印语句,注释掉那些你认为不再需要的语句。在整个程序运行之前不要删除它们。在

这能让你走吗?在

相关问题 更多 >

    热门问题