Skip to content
Sign upLog in
← Back to Community

How to make sprite follow mouse in pygame

Profile icon
Dunce

I would like to make a sprite rotate to face the cursor, in pygame, and I would like it to move in the direction of the cursor.
How would I do that?

Answered by Coder100 [earned 5 cycles]
View Answer
Voters
Profile icon
yzhacker
Profile icon
Dunce
Comments
hotnewtop
Profile icon
Coder100

That requires trig.

Step 1.

Calculate angle

import math ang = math.atan2(MOUSEY - PLAYERY, MOUSEX - PLAYERX)

replace those variables with you know what

Step 2.

Rotate the sprite with that angle

Step 3.

Move:

PLAYERX = math.cos(ang) PLAYERY = math.sin(ang)

**Note: ** Don't forget to replace the variables!

Also, if the player is in a fixed position on the screen, replace PLAYERY and PLAYERX with the y and x position of where the player is on the screen actually.

Profile icon
Dunce

@Coder100
Thanks!

Profile icon
Coder100