Moving a-rectangle and changing direction


#1

Hi, I am a complete beginner so bare with me!

I have created a rectangle using ofRectangle and I would like to the rectangle to constantly be moving around the screen and change direction when prompted by arrow key.

Is it as simple as writing x+ x_distance to move th shape and how would I change the direction of the rectangle? Some sample code would help. (I don’t have access to OF myself at the moment)


#2

Hi. I made an sample code for you, just copy and paste on your new project:

#include "ofApp.h"

int x, y;
//--------------------------------------------------------------
void ofApp::setup(){
    x = ofGetWidth()*0.5;
    y = ofGetHeight()*0.5;
}

//--------------------------------------------------------------
void ofApp::update(){

}

//--------------------------------------------------------------
void ofApp::draw(){
    ofSetColor(0); // Rectangle color.
    ofDrawRectangle(x, y, 100, 100);
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){
    switch (key) {
        case (OF_KEY_UP):
            y -= 10;
            break;
            case (OF_KEY_DOWN):
            y += 10;
            break;
            case (OF_KEY_LEFT):
            x -= 10;
            break;
            case (OF_KEY_RIGHT):
            x += 10;
            break;
        default:
            break;
    }
}

#3

Hi Thanks for your help, from what I can see your code allows the arrow key to move up/down/left/right but it doesn’t look like it’s constantly moving and moving in the direction of the arrow key