Summon
Summon

Reputation: 77

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.mouse.get_pos()

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        Running = False

mpos = (mx, my)
X = (playerX)
Y = (playerY)


if mpos[1] >= Y: 
    playerY += vel


if mpos[1] <= Y:
    playerY -= vel

    
if mpos[0] <= X:
    playerX -= vel

if mpos[0] >= X:
    playerX += vel

Upvotes: 3

Views: 86

Answers (1)

sloth
sloth

Reputation: 101072

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 = 10
    while True:
        
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                return 
                
        movement = pygame.mouse.get_pos() - pos 
        if movement.length() > 6: # some margin so we don't flicker between two coordinates
            if 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

Upvotes: 3

Related Questions