Control the speed of a ship and make it move on its own c ++

1

I would like to know if someone could explain two things to me, the first one to make a ship that moves alone until an x coordinate, and, the second as I can do to control the speed of the ship, my programming teacher told me to use some time, but I was investigating and I did not find how to control the speed.

Here is my code attempt, my logic is that the bool variables control the movement up, down, left right.

New info (Edited question)

SPECIFICATIONS

As I start with this object-oriented programming, it will be difficult for me to understand certain things, but I will make an effort to understand as much as possible (for example I still have problems with setting parameters both by value and by reference). p>

My ship must be able to move vertically and horizontally.

It must go from an x coordinate to a new x coordinate, or from a y coordinate to a new y coordinate.

When I get to that new coordinate I'm going to set it as its limit and that limit will change the trajectory of the ship.

Let's say that first it increases in y ++ and when I reach that limit it changes to x ++, before I did not make this specification and I confused with that, an apology, it should be able to move in all directions, but not horizontally.

I must control that this ship changes direction when I set its limit, so I put variables of type bool (I'll comment on them to specify), I'm going to put my code below the other one that I moved a bit but not I got a lot.

#include <iostream>
#include <conio.h>
#include "windows.h"
#include <stdio.h>

using namespace std;

void gotoxy(int x, int y){
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD dwPos;
    dwPos.X = x;
    dwPos.Y = y;
    SetConsoleCursorPosition(hcon, dwPos);
}
class Nave{
    public:
        int x,y;
        bool izqder;
        bool arrab = false;
        void imprime();
        void borrar();
};

void Nave::imprime(){
    system("color 0A");
    gotoxy(x,y); cout<<("** **");
    gotoxy(x,y+1); cout<<(" *** ");
    gotoxy(x,y+2); cout<<("  *  ");
}


void Nave::borrar(){
    gotoxy(x,y); cout<<"     "<<endl;
    gotoxy(x,y+1); cout<<"     "<<endl;
    gotoxy(x,y+2); cout<<"     "<<endl;
}

int main()
{
    system("mode con: cols=100 lines=50");
    Nave nave1;
        nave1.x=8; nave1.y=5;
        nave1.imprime();
    while(nave1.arrab = false){
        for(nave1.y; nave1.y<=50; nave1.y++){
            nave1.borrar();
                if(nave1.arrab == 50){
                nave1.arrab=true;
                }
            nave1.imprime();
        }
    }

    system("pause>nul");
    return 0;
}

THIS IS THE NEW CODE

        #include <iostream>
        #include <conio.h>
        #include "windows.h"
        #include <stdio.h>

        using namespace std;

        void gotoxy(int x, int y){
            HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
            COORD dwPos;
            dwPos.X = x;
            dwPos.Y = y;
            SetConsoleCursorPosition(hcon, dwPos);
        }
        class Nave{
            public:
                int x,y;
                float velocidad; //Vairable sugerida agregada
                bool izqder; //Variable para controlar eje x
                bool arrab; //Variable para controlar eje y
                void imprime();
                void borrar();
        };

        void Nave::imprime(){
            system("color 0A");
            gotoxy(x,y); cout<<("** **");
            gotoxy(x,y+1); cout<<(" *** ");
            gotoxy(x,y+2); cout<<("  *  ");
        }


        void Nave::borrar(){
            gotoxy(x,y); cout<<"     "<<endl;
            gotoxy(x,y+1); cout<<"     "<<endl;
            gotoxy(x,y+2); cout<<"     "<<endl;
        }

    /*Intente meter este fragmento (aporte de @PaperBirdMaster) 
pero no logré nada, no supe adpatarlo por cuiertas cosas que 
detallaré ahi mismo marcadas con un @ para distinguir que es mi comentario*/
    /*
    void mover_nave(Nave &nave, const Posicion &destino)
    //@No entiendo como funciona & en el parametro.
    //@No se para que sirve const
    {
        // Comprueba si la nave ya esta en su destino
        if (nave.posicion.x != destino.x && nave.posicion.y != destino.y)
        {
            /* Calcula cuanto tiempo ha pasado desde que se actualizo la nave
            por ultima vez. */
            auto ahora = std::chrono::steady_clock::now();
            std::chrono::duration<float> tiempo_pasado = ahora - nave.ultima_actualizacion;
/*@NO tengo ni la minima idea de como funciona este fragmento anterior
no se que sea todo esto de chrono*/

            // Calcula cuanto se habra desplazado la nave dada su velocidad.
            float desplazamiento = nave.velocidad * tiempo_pasado.count();

            // Usar trigonometria para calcular cuanto se desplaza la nave en cada eje.
            ...

            // Actualizar el estado.
            nave.ultima_actualizacion = ahora;
        }
    }
    */
        int main()
        {
            system("mode con: cols=100 lines=50");
            Nave nave1;
                nave1.x=8; nave1.y=5;
                nave1.imprime();
                nave1.arrab = false;
                for(int i=0; i<30; i++){
                    nave1.borrar();
                    gotoxy(nave1.x,nave1.y+i);
                    nave1.imprime();
                    Sleep(100);
                /*Con este for conseguí que el cursor se mueva hacia abajo, 
mas no conseguí que mi nave se moviera, 
me está fallando la lógica por en mi mente esto si funcionaría de esta manera*/


               }


            system("pause>nul");
            return 0;
        }

Note: I still did not add things related to the time because I did not understand how they worked, therefore I put a Sleep, and I thought to control the speed with the Sleep, but my teacher told me to do it with time (which is something that even I do not know why I thought to use Sleep).

I hope you understand it better now and there is someone who can support me, thank you very much to those who have already made their contribution.

    
asked by Axel A 02.11.2017 в 04:47
source

1 answer

5

You can not control the speed of something moving on the screen without first understanding the concept of Frames per second , copio from wikipedia:

  

Frames per second , also called refresh rate , images per second , frames per second , FPS (from English "frames per second") or framerate , is the speed (rate) at which a device displays images called frames or frames .

That is, the speed of anything you want to move around the screen will be linked to the speed that your program refreshes the data, both logical and visual.

Proposal.

Add a velocity value to your Nave object, I advise you that this value represents how many cells (characters) moves per second and that this is a floating point value. So a value of 1.5f will mean that a cell will move a half and a second (if you had to move 3 cells it would take two seconds).

You will also need to store when the ship was last updated, to calculate how much it would have moved since the last update. I advise you to type std::chrono::steady_clock::time_point .

Create a Posicion object that stores positions on the screen:

struct Posicion { float x{}, y{}; };

You can use it as a member of your ship instead of storing the coordinates separately. Use floating-point numbers to store intermediate trajectories (if less than one cell is displaced in a frame, the offset must be stored even if visually it does not cause any change).

Create a method mover_nave (call it what you want) that given a ship and a position move the ship provided a number of cells calculated based on the speed of the ship:

void mover_nave(Nave &nave, const Posicion &destino)
{
    // Comprueba si la nave ya esta en su destino
    if (nave.posicion.x != destino.x && nave.posicion.y != destino.y)
    {
        /* Calcula cuanto tiempo ha pasado desde que se actualizo la nave
        por ultima vez. */
        auto ahora = std::chrono::steady_clock::now();
        std::chrono::duration<float> tiempo_pasado = ahora - nave.ultima_actualizacion;

        // Calcula cuanto se habra desplazado la nave dada su velocidad.
        float desplazamiento = nave.velocidad * tiempo_pasado.count();

        // Usar trigonometria para calcular cuanto se desplaza la nave en cada eje.
        ...

        // Actualizar el estado.
        nave.ultima_actualizacion = ahora;
    }
}

Once you know the displacement of that frame, you must use Pythagoras to know how much it moves on each axis:

    
answered by 02.11.2017 в 09:24