【问题标题】:How can I make my circles move naturally instead of not receiving gravity when they collide?如何让我的圆圈在碰撞时自然移动而不是不受重力影响?
【发布时间】:2021-05-12 19:10:51
【问题描述】:

我正在尝试做一个简单的物理模拟,但是当圆圈与另一个圆圈碰撞时,它们会失去所有重力并粘在一起,这使得平衡它们非常容易,但它看起来很不自然,让你能够做结构违反物理定律的,例如this one。

代码:

from pygame.locals import *
import pygame
import sys

pygame.init()

green = (0, 255, 0)
circles = []
gravity = 1

def input():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            circles.append(list(event.pos))

def boundaries():
    for circle_pos in circles:
        if circle_pos[1] > 495:
            boundaries = circle_pos[1] - 495
            circle_pos[1] -= boundaries
        if circle_pos[0] < 5:
            boundaries2 = circle_pos[0]
            circle_pos[0] += boundaries2
        if circle_pos[0] > 995:
            boundaries3 = circle_pos[0] - 995
            circle_pos[0] -= boundaries3


def collision():
    for i, circle_pos_1 in enumerate(circles):
        for circle_pos_2 in circles[i + 1:]:
            dx = circle_pos_2[0] - circle_pos_1[0]  # circle_pos_2 = y val
            dy = circle_pos_2[1] - circle_pos_1[1]
            if dx * dx + dy * dy < 10 * 10:
                circle_pos_2[1] -= gravity
    for circle_pos in circles:
        pygame.draw.circle(screen, green, circle_pos, 5)


def wind():
    for circle_pos in circles:
        wind = 0
        for i in range(2):
            wind += 0.01
            circle_pos[0] -= wind


clock = pygame.time.Clock()
screen = pygame.display.set_mode((1000, 500))
while True:
    screen.fill((15, 15, 15))

    input()
    mouse_pos = pygame.mouse.get_pos()

    for circle_pos in circles:
        circle_pos[1] += gravity
    boundaries()

    collision()

    pygame.display.update()
    clock.tick(120)

【问题讨论】:

  • 这究竟会发生什么变化?

标签: python pygame game-physics physics


【解决方案1】:

我不了解 Python,但似乎在 collision() 中您明确声明如果第 1 圈和第 2 圈发生碰撞(或重叠),那么 第 2 圈的重力会消失。这会导致圆圈像雪花一样粘在一起。如果你想让它们相互滚动,你必须改变这个函数。

我建议你从一个更简单的问题开始:一个圆和一个斜面。您似乎已经假设下落的圆圈应该具有恒定的速度,就像一颗沉入水中的鹅卵石;将其扩展到在斜面上滑动的一种简单方法是让圆以随角度正弦变化的速度滑动。

一些捷径是可能的,但如果最后一段对您来说没有意义,那么您必须复习三角学和基础物理学。 如果不了解一些基本物理学,你就不可能让这个程序运行。

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    相关资源
    最近更新 更多