나는 간단한 중력을 시뮬레이트하기 위해 파이 게임으로 코드를 만들려고 노력해 왔습니다. 현재 태양 주위를 공전하고있는 물체 (HOM)는 하나뿐입니다. 그러나 나에게 알려지지 않은 이유 때문에, 코드를 실행할 때마다 HOM은 처음에는 궤도를 따라 태양을 돌고, 수직으로부터 135도에 도달하면 멀리 멀리 태양으로부터 가속합니다.중력 문제
왜 이런 일이 발생하고 어떻게 해결할 수 있는지 아는 사람이 있습니까? 문제를 해결하기 위해 몇 가지 변수를 인쇄했지만 지금까지 행운이 없었습니다.
코드 :
import pygame,sys,time
from math import *
screen=pygame.display.set_mode((800,600))
G = 5
class Object: #Just an object, like a moon or planet
def __init__(self,mass,init_cds,init_vel,orbit_obj='Sun'):
self.mass = mass
self.cds = init_cds
self.velocity = init_vel
self.accel = [0,0]
self.angle = 0
self.orb_obj = orbit_obj
def display(self):
int_cds = (round(self.cds[0]),round(self.cds[1]))#Stores its co-ordinates as floats, has to convert to integers for draw function
pygame.draw.circle(screen,(255,0,0),int_cds,10)
def calc_gravity(self):
if self.orb_obj == 'Sun':
c_x,c_y = 400,300
c_mass = 10000
else:
c_x,c_y = self.orb_obj.cds
c_mass = self.orb_obj.mass
d_x = self.cds[0]-c_x
d_y = self.cds[1]-c_y
dist = sqrt(d_x**2+d_y**2) #Find direct distance
angle = atan(d_x/d_y) #Find angle
print(d_x,d_y)
print(dist,degrees(angle))
if dist == 0:
acc = 0
else:
acc = G*c_mass/(dist**2) #F=G(Mm)/r^2, a=F/m -> a=GM/r^2
print(acc)
acc_x = acc*sin(angle) #Convert acceleration from magnitude+angle -> x and y components
acc_y = acc*cos(angle)
self.accel = [acc_x,acc_y]
print(self.accel)
self.velocity = [self.velocity[0]+self.accel[0],self.velocity[1]+self.accel[1]] #Add acceleration to velocity
print(self.velocity)
self.cds = (self.cds[0]+self.velocity[0],self.cds[1]+self.velocity[1]) #Change co-ordinates by velocity
print(self.cds)
print('-------------------') #For seperating each run of the function when printing variables
HOM = Object(1000000,(400,100),[10,0]) #The problem planet
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((0,0,0))
pygame.draw.circle(screen,(255,255,0),(400,300),25)
HOM.display()
HOM.calc_gravity()
clock.tick(30)
pygame.display.flip()
출력 값의 스 니펫을 게시 할 수 있습니까? – Petar
물론 문제가 발생한 시간대의 값을 격리했습니다. print 문은 변수의 순서가 인쇄 된 것을 알려줍니다. – Oliver
'------------------- 63.844549149787156 21.125165327178536 67.24878486813137 71.6914260165494 11.056078702397329 [10.496403191570936, 3.4730960703071965] [-6.9922567082937785, 29.012459884108917] (456.8522924414934, 350.13762521128746) - ------------------ 56.852292441493375 50.13762521128746 48.59116240316936 8.701759117372143 75.80214124733293 [6.526398145958425, 5.755583287313254] [-0.4658585623353533, 34.76804317142217] (456.386433879158, 384.9056683827096) ---- ---------------' – Oliver