Rotate image with PVectors for game

For a project, I am making a simple top down shooter and I’m trying to incorporate a push pop rotation to the player character. I am having trouble having the character image rotate to the mouse coordinates ala pointing a gun while moving.

calls classes used and loads in PVector and image data for the player class
Player player = new Player();
Screens screen = new Screens();

void setup() {
playerSprite = loadImage(“test.png”);
playerSprite.resize(100, 100);
player.playerPos.set(300, 570);

class Player {
final PVector playerPos = new PVector();
float angle = 0;
float targetAngle = 0;
float easing = 0.05f;

// player image
void displayPlayer() {

angle = atan2(playerPos.y - mouseY, playerPos.x - mouseX);

float dir = (angle - targetAngle) / TWO_PI;
dir -= round( dir );
dir *= TWO_PI;

targetAngle += dir * easing;

pushMatrix();
translate( playerPos.x, playerPos.y );
rotate( targetAngle );
image(playerSprite, playerPos.x, playerPos.y);
popMatrix();

}

1 Like

I can post my full code on request but Im having trouble having ONLY the player character rotate with the mouse and moving naturally in the game

your code looks good - usage of pushMatrix and popMatrix

good use of atan2

What is not working exactly?

Hi @boomstick55

Welcome to our community! :slight_smile:

Since you didn’t post the full code version it is hard to test your code. However, my guess is that you should put

image(playerSprite, 0,0);

Because you already translate the image to the player’s position

Hope it helps! :slight_smile:

2 Likes

My sprite was flying all over the screen previously but this is what I needed!

Thank you so much!

1 Like