Rotating player to always face the direction of the cursor (python)

So in my game, I want the player character to always look in the direction of the cursor.

Here is my relevant code:

def setup():
    size(1440, 780)

playerX = width / 2
playerY = height / 2
playerSpeed = 0.05
    
def draw():
  background(255)
  global playerX, playerY, playerSpeed, differenceY, differenceX

  player = loadImage("player.png")
  
  if (abs(mouseX - playerX) > 1) and (abs(mouseY - playerY) > 1): 
    targetX = mouseX 
    targetY = mouseY
    differenceX = targetX - playerX
    differenceY = targetY - playerY
    playerX = playerX + differenceX * playerSpeed
    playerY = playerY + differenceY * playerSpeed
  
  angle = (180 / PI) * -atan2(differenceY, differenceX)
  rotate(int(angle))
  image(player, playerX-55, playerY-55, 110, 110)

However, when running the code, some really weird glitching thing happens (which to my understanding is because it rotates around the origin?). Anyway, I searched online for an answer and I think this website, python - How can I make the player "look" to the mouse direction? (Pygame / 2D) - Game Development Stack Exchange, pretty much answers my question.

But it has a different type (?) of code that is different to processing python. I identified the line of code I need to hopefully make it work, which is:

    self.rect = self.image.get_rect(center=self.position)

but Iā€™m not sure how to convert it to processing python. Does anyone know how to do so? Or any other alternate ways of making the player face the direction of the cursor? Thank you!

Maybe changing imageMode() to CENTER in setup() would make things easier: :man_shrugging:

1 Like

Perhaps an approach like this?

def setup():
    global player
    size(800, 800)
    player = loadImage('player.png')
    
def draw():
    background(255)
    # move origin to centre of display window
    translate(width/2, height/2)
    a = atan2(mouseX-width/2, mouseY-height/2)
    # rotate entire coordinate space
    rotate(a*-1)
    image(player, -55, -55, 110, 110)

You may need to include pushMatrix() and popMatrix() functions in your program where you need to isolate the effects of any transformations (translate(), rotate(), etc.).

2 Likes