Skip to content Skip to sidebar Skip to footer

Make Moving More Realistic

I made this code to make a circle follow my mouse but the movement is really mechanic and does not give the 360 degrees of movement I desired. Here's the code: mx, my = pygame.mous

Solution 1:

You need to calculate the direction vector, normalize it and multiply it with the desired speed, then apply that to the circles position.

The easiest way is to use pygame's built-in Vector2 class for this:

import pygame

def main():
    pygame.init()
    screen = pygame.display.set_mode((600, 600))
    pos = pygame.Vector2()
    clock = pygame.time.Clock()
    speed = 10while True:
        
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                return 
                
        movement = pygame.mouse.get_pos() - posif movement.length() > 6: # some margin so we don't flicker between two coordinatesif movement.length() > 0: # when we move, we want to move at a constant speed
                movement.normalize_ip()
            pos += movement * speed # change the position
    
        screen.fill((20, 20, 20))
        pygame.draw.circle(screen, 'dodgerblue', pos, 30)
        pygame.display.flip()
        clock.tick(30)
        
main()

enter image description here

Post a Comment for "Make Moving More Realistic"