根据PYGAME中触摸的墙壁制作一个矩形弹跳

时间:2018-03-13 19:20:07

标签: python pygame coordinates

我试图制作一个矩形弹跳,没有偏离极限。 我希望我的矩形能够根据触摸的墙壁反弹。 在这段代码中,我试图以90º的角度弹回矩形,但它不起作用。

我用它来计算每一笔进步:

 rect_x += rectxSpeed
 rect_y += rectySpeed

达到极限时

if rect_y>450 or rect_y<0:
    rectySpeed=5
    rect_y=rectySpeed*-(math.pi/2)

if rect_x>650 or rect_x<0:
    rectxSpeed=5
    rectx_y=rectxSpeed*-(math.pi/2)

这里的整个代码:

import pygame
import random
import math
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
rect_x= 50.0
rect_y = 50.0
rectxSpeed=5
rectySpeed=5

pygame.init()

# Set the width and height of the screen [width, height]
size = (700, 500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while not done:
    # --- Main event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # --- Game logic should go here

    # --- Screen-clearing code goes here

    # Here, we clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.

    # If you want a background image, replace this clear with blit'ing the
    # background image.
    screen.fill(BLACK)
    string=str(rect_x)
    string2=str(rect_y)
    string3="["+string+"]"+"["+string2+"]"
    font = pygame.font.SysFont('Calibri', 25, True, False)
    text = font.render(string3,True,RED)
    screen.blit(text, [0, 0])    
    #Main rectangle
    pygame.draw.rect(screen, WHITE, [rect_x, rect_y, 50, 50]) 
    #Second rectangle inside the rectangle 1
    pygame.draw.rect(screen, RED, [rect_x+10, rect_y+10, 30, 30])  
    rect_x += rectxSpeed
    rect_y+=rectySpeed
    if rect_y>450 or rect_y<0:
        rectySpeed=5
        rect_y=rectySpeed*-(math.pi/2)
    if rect_x>650 or rect_x<0:
        rectxSpeed=5
        rect_x=rectxSpeed*-(math.pi/2)

    # --- Drawing code should go here

    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 60 frames per second
    clock.tick(20)

# Close the window and quit.
pygame.quit()

¿我如何调整前进?

这段代码产生了这个:

This code produce this

通过以下方式更改到达限制代码:

if rect_y>450 or rect_y<0:
    rectySpeed=rectySpeed*-(math.pi/2)

   if rect_x>650 or rect_x<0:
    rectxSpeed=rectxSpeed*-(math.pi/2)

产生这个:

1 个答案:

答案 0 :(得分:0)

我认为重要的是要认识到这里矩形对象的速度是一个标量值,而不是它的矢量对应 velocity 。您试图将rectySpeed(标量值)乘以-(math/pi)/2,这是一个将以弧度形式返回的值,如@ 0x5453所述。只要矩形根据它所接触的墙壁而不同地弹跳,您就没有指定要施加的不同约束。我想你可能想要考虑为什么你希望矩形始终以90°角反弹。请注意,始终以90°角度反弹的矩形会给播放器/用户带来一些非常奇怪的功能。

从水平方向测量的矩形接近墙壁的角度将等于矩形从墙壁的垂直线到其新路径测量的从墙壁上反弹的角度(在x-的情况下)定向反弹)。

就准确的物理引擎而言,在矩形与墙壁接触的情况下,您可能需要考虑将机制简化为以下内容:

if rect_y>450 or rect_y<0:
    rectySpeed=rectySpeed*-1

if rect_x>650 or rect_x<0:
    rectxSpeed=rectxSpeed*-1

以上确保矩形对象只是改变方向,因此矩形速度的大小不会改变,但速度确实因为它是矢量。