Pygame先转到x位置,然后再转到y位置,再返回x位置n次

2024-05-23 23:26:25 发布

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

我试着先把我的播放器移动到我的飞船位置,然后返回unitsleft,然后根据剩余的单位再次进入飞船n次,这是我的代码。 我认为运动的概念不错,但我认为代码可能是错的。 感谢大家: 这是我的密码:

我以unitsize=2为例,但它最多可以是4

 if self.hasunit == False and self.isreturning == False:
        # If player collides with unit
        if pygame.sprite.spritecollide(self, unit_group, False):
            # OBTENER COORDENADAS DE X Y Y DE LA UNIDAD
            unitx = self.rect.x
            unity = self.rect.y
            # IF UNIT IS ONE
            if unitsize == 1:
                self.carrryingunit += unitsize
                self.hasunit = True
                self.isreturning = False
            # IF UNIT IS BIGGER THAN ONE
            elif unitsize > 1:
                self.unitsleft = unitsize
                self.hasunit = True
                self.isreturning = True

由于上面的代码是在hasunit=True和isreturning=True的情况下,这意味着他必须去飞船x和飞船y,一旦它到达那里,重新运行unitx和unity,返回飞船坐标,以此类推,这是我的另一个代码

#UNIT IS BIGGER THAN ONE SO IT HAS UNIT AND ITS GOING TO RETURN
    elif self.hasunit == True and self.isreturning == True:
        #EXAMPLE 2 UNITSLEFT WOULD HAVE TO GO FIRST TO SPACESHIP, ONCE COLLIDED WITH SPACESHIP, GO TO UNITX AND UNITY AND THEN TO SPACESHIP AGAIN
        while self.unitsleft < 0:
            if (self.rect.x > spaceship_x):
                dx -= 1
            else:
                dx += 1
            if (self.rect.y < spaceship_y):
                dy += 1
            else:
                dy -= 1
            if pygame.sprite.spritecollide(self, spaceship_group, False):
                if (self.rect.x > unitx):
                    dx -= 1
                else:
                    dx += 1
                if (self.rect.y < unity):
                    dy += 1
                else:
                    dy -= 1
                if pygame.sprite.spritecollide(self, unit_group, False):
                    if (self.rect.x > spaceship_x):
                        dx -= 1
                    else:
                        dx += 1
                    if (self.rect.y < spaceship_y):
                        dy += 1
                    else:
                        dy -= 1
                self.unitsleft -= 1
            self.hasunit = False
            self.isreturning = False

另外,我想实现的另一件事是在上次碰撞中摧毁那个物体(单位),希望我的解释清楚,谢谢大家!)


Tags: torectselffalsetrueifelsedy
1条回答
网友
1楼 · 发布于 2024-05-23 23:26:25

您没有描述如果运行代码会发生什么,哪些不起作用,因此我发现很难确切地说出哪些不起作用。另一方面,我认为有一种更简单的方法来解决这个问题,而不是进行碰撞检测和有这么多if语句,这就是我的答案

当有事物交替时,我总是喜欢考虑使用正弦或余弦函数。我的解决方案使用余弦函数。原因是这些函数总是返回一个介于-1和1之间的值,这取决于作为参数传入的值。余弦以以下方式映射输入参数值(您可以看到它是交替的)

[0, pi] -> [1, -1] and [pi, pi * 2] -> [-1, 1] and so on...

在你的例子中,我们可以创建一个从玩家到宇宙飞船的方向向量,这个方向向量受这个余弦值的影响,这样它可以在朝向飞船和返回飞船的原始位置之间切换

这里有一个例子。我试着对它进行评论,但可以随意提出任何问题

import pygame
import sys
import math

startPos = [50, 50]

#set player pos to start pos. Notice it is
#copied by value because we will need startPos
#later
playerPos = startPos[:]
playerLastFrame = startPos[:]

#targerPos is where your spaceship is
targetPos = [400, 500]

#calculate the direction and distance once
direction = (targetPos[0] - playerPos[0], targetPos[1] - playerPos[1])
totalDistance = math.hypot(*direction)

#create a unit direction vector 
unitDir = (direction[0] / totalDistance, direction[1] / totalDistance)

speed = 0.001

#as you can see from the cosine mapping above,
#cos(math.pi) is 0, which is at the starting pos.
#1 is the destination. You can start at the destination
#by setting angle to 0.
angle = math.pi

#the number of rounds you want to travel
nRounds = 2

#total distance travelled. This will be used to
#determine whether or not to stop
totalDistanceTravelled = 0

pygame.init()
window = pygame.display.set_mode((600, 600))

while True:
    events = pygame.event.get()

    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    #alpha is simply what ever the cos function returns
    #mapped between 0 and 1 since its easier to work with.
    alpha = (math.cos(angle) + 1) * 0.5

    #only want to keep travelling if the total distance is
    #less than what how much we want to travel i.e travel nRounds
    #times
    if totalDistanceTravelled  <  totalDistance * nRounds:
        #the rate at which the angle is incremented
        #can be used to simulate speed because the
        #faster we increment it the faster alpha will change.
        angle += speed

    #current distance is some fraction of totalDistance.
    #Since we have mapped alpha from 0 to 1, currentDistance
    #will go from 0 to totalDistance.

    #   alpha    currentDistance
    #  [0, 1] -> [0, totalDistance]
    currentDistance = alpha * totalDistance
    playerLastFrame = playerPos[:]

    # set the players position 
    playerPos[0] = (unitDir[0] * currentDistance) + startPos[0]
    playerPos[1] = (unitDir[1] * currentDistance) + startPos[1]

    
    totalDistanceTravelled += math.hypot(abs(playerLastFrame[0] - playerPos[0]), abs(playerLastFrame[1] - playerPos[1]))

    window.fill((255, 255, 255))
    
    pygame.draw.circle(window, (0, 255, 0), startPos, 5)
    pygame.draw.circle(window, (255, 0, 0), targetPos, 5)
    pygame.draw.circle(window, (0, 0, 0), (playerPos[0], playerPos[1]), 6)

    pygame.display.flip()

相关问题 更多 >