簡體   English   中英

對象已創建,但OOP版本中沒有任何移動

[英]Objects are created but there is no movement in OOP Version

我正在編寫太陽系的OOP版本。 當我運行它時,將創建對象,並且距離和半徑也是正確的。 但是行星不動。 但是我有一個功能,所以它們應該繞着太陽轉。 我收到一個名稱錯誤:NameError: name 'planetSphere' is not defined 我嘗試刪除def setspeed部分。 然后我可以通過打印看到它的工作原理,因為軸數發生了變化,但是我看不到模擬本身中行星的任何變化。 整個代碼: https : //trinket.io/python/e2b520c570

 planets = []


class Sphere(object):
    def __init__(self, pos, radius, make_trail):
        self.pos = pos
        self.radius = radius
        self.make_trail = make_trail



class planet(Sphere):

    def __init__(self, pos, radius, make_trail, mass, velocity):
        super().__init__(pos, radius, make_trail)
        self.mass = mass
        self.velocity = velocity
        planetSphere = sphere (pos = self.pos, radius = self.radius, make_trail = self.make_trail, mass = self.mass, velocity = self.velocity)

    def setPosition(self, newPos ):
        planetSphere.pos = newPos
        print(planetSphere.pos)


sun = planet(pos=vec(0,0,0),radius=s_rad1*1.5, make_trail=True, mass=2e30, velocity=vec(0,0,0))

#Other objects

planets.extend((mercury,venus,earth,mars,jupiter,saturn,uranus,neptun,pluto))

dt = 10000
time = 0.1


while True:

    rate(framerate) 
    print(earth.pos)



    #for-Schlaufe für Berechnung jedes einzelnen Planeten


    for planet2 in planets:
        g_force = vec(0,0,0)
        for planet1 in planets:
            if planet2 != planet1:
                g_force += g * planet1.mass * planet2.mass * (planet1.pos - planet2.pos).norm()  / (planet1.pos - planet2.pos).mag2
        #print((sun.pos - planet.pos).mag2)




        #print(sun.pos)

        #Änderung des Velocity Vektor wird zum alten addiert
        #Da a=F/m // V = a*t(a*dt) 2 Geschw. vektoriell durch F/m ausgedrückt.
            planet2.velocity = planet2.velocity + ( (g_force) / planet2.mass) * 1000 #Richtungsänderung

        #Diese Änderung wird zur alten Position addiert = neue Position
            planet2.pos += planet2.velocity * 1000
            newPos = planet2.pos
            planet2.setPosition(newPos)
def setPosition():
    #planetSphere.pos = self.pos
    print(planetSphere.pos)

是在行星類內部定義的。 因此,方法期望的第一個參數是“自我”。

另外,按照思路,這可能是您要尋找的內容:

def setPosition(self,newPos):
    planetSphere.pos = newPos
    print(planetSphere.pos)

您是否嘗試過Planet類的init方法來制作planetSphere => self.planetSphere? 這是我的意思:

class planet(Sphere):

def __init__(self, pos, radius, make_trail, mass, velocity):
    super().__init__(pos, radius, make_trail)
    self.mass = mass
    self.velocity = velocity
    self.planetSphere = sphere (pos = self.pos, radius = self.radius, make_trail = self.make_trail, mass = self.mass, velocity = self.velocity)

def setPosition(self, newPos ):
    self.planetSphere.pos = newPos
    print(planetSphere.pos)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM