In class we did a program on moving a round object up and down on a form,we finally figured it out but what i want to know is there are another way of shortening the coding instead of tesing using boolean :(

Dani AI

Generated

raised a common question: you can make the movement both shorter and clearer than repeated boolean checks, but terseness and readability trade off. showed the straightforward per-frame checks, suggested a compact arithmetic trick, and correctly warned that very short expressions can hurt clarity. A robust middle ground is to store a single velocity/direction and update that from key events; the update loop then only applies that velocity.

int yPos = 100;
int vy = 0;
const int SPEED = 2; // pixels per tick

// key-down handler
void onKeyDown(int key) {
    if (key == KEY_UP)   vy = -SPEED;
    else if (key == KEY_DOWN) vy = SPEED;
}

// key-up handler
void onKeyUp(int key) {
    if (key == KEY_UP && !isKeyPressed(KEY_DOWN)) vy = 0;
    else if (key == KEY_DOWN && !isKeyPressed(KEY_UP)) vy = 0;
}

// main loop
void update() {
    yPos += vy;
    yPos = clamp(yPos, 0, WINDOW_HEIGHT - SPRITE_H);
}

Why this helps: it keeps the per-frame update tiny and readable, cleanly handles simultaneous presses (decide whether they cancel or one takes precedence), and makes it easy to add speed, acceleration, or delta-time scaling later. If you prefer maximum terseness you can derive a signed direction from key states (that’s what ’s idea does), but that sacrifices explicitness and can be confusing when both keys register.

Practical notes: clamp the position to the window, use consistent naming (vy, SPEED) and multiply by dt for frame-rate independence if you have variable timestep. The event-driven velocity pattern scales well if you later add horizontal movement, diagonal motion, or smoothing.

Recommended Answers

All 5 Replies

My crystal ball is in the repair shop, unfortunately, so I don't know whether any solution I might come up with is shorter or longer than yours.

Why dont you post your program or at least a part of it here so that others could get to know how long (or short) you program is at the moment :D

-----------------

Here you go.

if(upkeypressed)
{
    yPos--;
}
if(downkeypressed)
{
    yPos++;
}

Assuming that upkeypressed and downkeypressed are booleans or integers that only have values 0 or 1,

yPos += downkeypressed - upkeypressed;

you can do it that way, but yo loose alot of readability!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.