Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a rectangle in a curved path in pygames?

Tags:

python

pygame

moving a rectangle in a straight line on pygames is easy. But how do i implement gravity into the rectangle's path? Like instead of a straight path, move in an curved path. Perhaps, the image below will help you understand what i am trying to achieve. Curved path

Here is the code to move the rectangle in a straight path to the left.

import pygame
import time

pygame.init()
white = (255,255,255)
black = (0,0,0)
display_width = 800
display_height  = 700
gameDisplay = pygame.display.set_mode((display_width,display_height))
clock = pygame.time.Clock() 
FPS = 30

x = 300
y = 100
while True:
    x -= 10
    gameDisplay.fill(white)
    pygame.draw.rect(gameDisplay, black, (x, y, 50,50))
    pygame.display.update()
    clock.tick(FPS)
like image 566
user859385 Avatar asked Nov 30 '25 22:11

user859385


1 Answers

y_speed = 0
x_speed = -10
gravity = -3 # Depending on how fast you want gravity to be
while True:
    x += x_speed
    y += y_speed
    y_speed += gravity
    gameDisplay.fill(white)
    pygame.draw.rect(gameDisplay, black, (x, y, 50,50))
    pygame.display.update()
    clock.tick(FPS)

Having taken some Physics can help with programming. I would suggest looking into some basic kinematic equations if you're still confused

like image 179
MANA624 Avatar answered Dec 03 '25 13:12

MANA624



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!