How to set up a sprite to rotate and move on a screen.

edited February 2018 in How To...

Hello,

I am trying to write code that will allow a preprogrammed sprite to move according to input from the WSAD keys. Currently, I am defining a sprite as a custom class with an x, y position, a width, and a height. I have the ability to program the code so each key moves the sprite in a corresponding direction.

W - Up, S - Down, A - Left, D - Right

What I want to do is edit this code slightly. I want to build it so the keys function like this:

W - Up, S - Down, A - Rotates the sprite left around the center point, D - Rotates the sprite right around the center point

I am looking at the rotate() and translate() functions now, just a little unclear on how to properly use them. I can make the sprite rotate around a point, but when I move the sprite off of that point (using either W or S) the sprite continues to rotate around the original position. How do I write the code to adjust the position with the new x, y coordinates?

Thanks for the help.

Tagged:

Answers

  • edited February 2018 Answer ✓

    You need to move the origin of your coordinate system to be at the center of the sprite. Right now you are probably drawing your sprite at a position (x,y):

    image(sprite, x, y);
    

    Convince yourself this does the same thing:

    pushMatrix();
    translate(x,y);
    image(sprite,0,0);
    popMatrix();
    

    Next try this:

    pushMatrix();
    translate(x,y);
    rotate(map(millis()%5000,0,5000,0,TWO_PI));
    image(sprite,0,0);
    popMatrix();
    

    Notice the sprite does rotate - but it rotates around the top left corner. We need to move the origin a little more!

    pushMatrix();
    translate(x+(sprite.width/2),y+(sprite.height/2));
    rotate(map(millis()%5000,0,5000,0,TWO_PI));
    image(sprite,-sprite.width/2,-sprite.height/2);
    popMatrix();
    

    See the reference to learn about what these functions do.

  • Thank you TfGuy44 and GoToLoop. I'll look over these examples. You guys are awesome!!!

Sign In or Register to comment.