I need to rotate my image and then be able to move it properly

Hi, I'm making a tank game and I need to be able to rotate the tanks with the arrow keys and then if I press forward, they will move towards the direction that they are facing. I managed to rotate them, but I can't figure out how to move them forwards according to their rotation. Here is my code:

void draw() { if (keys[2]) { tankRotate1-=tankRSpeed1; } if(keys[3]) { tankRotate1+=tankRSpeed1; } imageMode(CENTER); pushMatrix(); translate(tankX1, tankY1); rotate(radians(tankRotate1)); image(redTnak, 0, 0); popMatrix(); }

Let me know if more code is needed. I appreciate any help that I can get!


  • Answer ✓

    You need to update your tanks position based on it's rotation in addition to which keys are pressed:

    float px, py;
    float r;
    void setup(){
    void draw(){
    void keyPressed(){
      if(keyCode==UP){ px+=6*cos(r); py+=6*sin(r); }
      if(keyCode==DOWN){ px-=6*cos(r); py-=6*sin(r); }
      if(keyCode==LEFT) r-=.05;
      if(keyCode==RIGHT) r+=.05;
  • THANK YOU SO MUCH! I've been looking everywhere for something like that!

  • Actually, when I tried playing your code, in some directions, it behaves strangely (if you press up sometimes, it will go sideways and others, it will behave normally) how would I fix that?

  • When you press up, it goes in the direction the triangle points.

Sign In or Register to comment.