Ir ao conteúdo

Cambalinho

Membro Pleno
  • Posts

    902
  • Cadastrado em

  • Última visita

posts postados por Cambalinho

  1. consegui melhores resultados:

    double GetRadians(int Degrees)
    {
        return (Degrees*M_PI/180);
    }
    
    void DrawRayLine(double X0, double Y0, double Radians, int Width,int Walls[10][10], int WallWidth, int WallHeight)
    {
        double adjustedRadians = fmod(Radians, 2 * M_PI);
    
        double X1 = X0 + cos(adjustedRadians) * Width;
        double Y1 = Y0 + sin(adjustedRadians) * Width;
    
        if (X1 < X0)
        {
            double temp = X0;
            X0 = X1;
            X1 = temp;
        }
    
        double dx = abs(X1 - X0);
        double dy = abs(Y1 - Y0);
    
        double Steps;
        double x = X0;
        double y = Y0;
         if (dx >dy)
            Steps = dx;
        else
            Steps = dy;
        // Calcular incrementos
        double INCREMENTO = 5.0;
        double Xincrement =  (dx / Steps) * INCREMENTO;
        double Yincrement =  (dy / Steps) * INCREMENTO;
    
        // Restante do código para desenhar o raio
    
        // Verificar se toca em uma parede
    
        bool hitsWall = false;
        int S=0;
        while (x < X1 || y < Y1)
        {
            int currentX = static_cast<int>(x /32);
            int currentY = static_cast<int>(y /32);
            //cout << x << "\t" << y <<"\n";
            if (currentX >= 0 && currentX < WallWidth && currentY >= 0 && currentY < WallHeight)
            {
                if (Walls[currentY][currentX] != 0)
                {
                    hitsWall = true;
                    break;
                }
            }
    
            x += Xincrement;
            y += Yincrement;
            S++;
        }
        MessageBox (NULL,to_string(S).c_str(), "hello",MB_OK);
        HDC HDCConsole = GetWindowDC(GetConsoleWindow());
        HPEN LineColor = CreatePen(0,1,RGB(255,0,0));
        HPEN OldPen =(HPEN)SelectObject(HDCConsole,LineColor);
        MoveToEx(HDCConsole,X0,Y0,nullptr);
        LineTo(HDCConsole,x,y);
        SelectObject(HDCConsole,OldPen);
        DeleteObject(LineColor);
    }
    
    HDC HDCConsole = GetWindowDC(GetConsoleWindow());
    
    int main()
    {
        int LevelMap[10][10]=
        {
            {1,1,1,1,1,1,1,1,1,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,1,0,0,1},
            {1,0,0,0,0,1,0,0,0,1},
            {1,0,0,0,0,0,1,0,0,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,1,1,1,1,1,1,1,1,1}
        };
        HBRUSH WhiteSquare=CreateSolidBrush(RGB(255,255,255));
        HBRUSH BlueSquare=CreateSolidBrush(RGB(0,0,255));
        HBRUSH OldBrush;
        for(int X=0, Y=0;Y<10;)
        {
    
            if(LevelMap[Y][X]==1) OldBrush=(HBRUSH)SelectObject(HDCConsole,BlueSquare);
            if(LevelMap[Y][X]!=1) OldBrush=(HBRUSH)SelectObject(HDCConsole,WhiteSquare);
            Rectangle(HDCConsole,X*32,Y*32,X*32+35,Y*32+35);
            X++;
            if(X>=10)
            {
                X=0;
                Y++;
            }
            SelectObject(HDCConsole,OldBrush);
        }
        DeleteObject(WhiteSquare);
        DeleteObject(BlueSquare);
        DrawRayLine(3.5*32,3.5*32,GetRadians(45),10000,LevelMap,10,10);
        cin.get();
        return 0;
    }

    noto 1 problema: se 45º é anti-horario porquê este resultado da linha vermelha?
    image.thumb.png.22c883215a558b57b3e6e956064de5c1.png

    • Curtir 1
  2. sim... estou a tentar:

    void DrawRayLine(int X0, int Y0, float Radians, int Width,int Walls[10][10], int WallWidth, int WallHeight)
    {
        int X1 = X0 + static_cast<int>(cos(Radians) * Width);
        int Y1 = Y0 + static_cast<int>(sin(Radians) * Width);
    
        int dx = abs(X1 - X0);
        int dy = abs(Y1 - Y0);
    
        double Steps;
        double x = X0;
        double y = Y0;
    
        // Calcular incrementos
        double INCREMENTO = 32.0;
        double Xincrement = INCREMENTO * cos(Radians);
        double Yincrement = INCREMENTO * sin(Radians);
    
        // Restante do código para desenhar o raio
    
        // Verificar se toca em uma parede
    
        bool hitsWall = false;
        while (x < X1 || y < Y1)
        {
             int currentX = static_cast<int>(x /32);
            int currentY = static_cast<int>(y /32);
            //cout << x << "\t" << y <<"\n";
            if (currentX >= 0 && currentX < WallWidth && currentY >= 0 && currentY < WallHeight)
            {
                if (Walls[currentX][currentY] != 0)
                {
                    hitsWall = true;
                    break;
                }
            }
    
            x += Xincrement;
            y += Yincrement;
        }
        HDC HDCConsole = GetWindowDC(GetConsoleWindow());
        HPEN LineColor = CreatePen(0,1,RGB(255,0,0));
        HPEN OldPen =(HPEN)SelectObject(HDCConsole,LineColor);
        MoveToEx(HDCConsole,X0,Y0,nullptr);
        LineTo(HDCConsole,x,y);
        SelectObject(HDCConsole,OldPen);
        DeleteObject(LineColor);
    }
    
    int main()
    {
        int LevelMap[10][10]=
        {
            {1,1,1,1,1,1,1,1,1,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,1},
            {1,1,1,1,1,1,1,1,1,1}
        };
    
        for(int X=0, Y=0;Y<10;)
        {
            HDC HDCConsole = GetWindowDC(GetConsoleWindow());
            Rectangle(HDCConsole,X*32,Y*32,X*32+31,Y*32+31);// ainda não comparo os valores para mudar a cor
            X++;
            if(X>=10)
            {
                X=0;
                Y++;
            }
        }
        DrawRayLine(3*32,3*32,25*3.14/180,200,LevelMap,10,10);
        cin.get();
        return 0;
    }

    este exemplo desenha a linha desejada, mas a linha termina no interior do quadrado e não no inicio do quadrado.... por usar o 32. e isso pode variar com o angulo.

    • Curtir 1
  3. tem razão amigo... por isso alterei o código:

    void DrawLineAngle(int X0, int Y0, float Radians, int Width)
    {
        int X1 = X0 + cos(Radians)*Width;
        int Y1 = Y0 + sin(Radians)*Width;
        int dx = abs(X1-X0);
        int dy = abs(Y1-Y0);
        double Steps;
        double x=X0;
        double y=Y0;
        HDC HDCConsole = GetWindowDC(GetConsoleWindow());
        HPEN LineColor = CreatePen(0,1,RGB(255,0,0));
        HPEN OldPen =(HPEN)SelectObject(HDCConsole,LineColor);
    
        const double INCREMENTO = 32.0;
        if (dx >dy)
            Steps = dx;
        else
            Steps = dy;
        double Xincrement = (dx / Steps) * INCREMENTO;
        double Yincrement = (dy / Steps) * INCREMENTO;
        int v=0;
    
        while(x<=X1 and y<=Y1)
        {
            x = x + Xincrement;
            y = y + Yincrement;
            v++;
        };
        if(x>X1) x=X1;
        if(y>Y1) y=Y1;
        cout << "Steps: " << v << "\n";
        MoveToEx(HDCConsole,X0,Y0,nullptr);
        LineTo(HDCConsole,x,y);
        SelectObject(HDCConsole,OldPen);
        DeleteObject(LineColor);
    }

    agora funciona 😉

    muito obrigado.

    esta função pode ser usada ou atualizada para usar numa grelha com quadrados de 32 por 32?(mesmo que só passe 3 ou 4 pixels no mesmo quadrado)

    • Curtir 1
  4. eis a minha função atual para desenhar 1 linha com 1 comprimento e Radianos:

    void DrawLineAngle(int X0, int Y0, float Radians, int Width)//Width é 100
    {
        int X1 = X0 + cos(Radians)*Width;//200
        int Y1 = Y0 + sin(Radians)*Width;
        cout << "X1: " << X1<< "\n";
        int dx = abs(X1-X0);
        int dy = abs(Y1-Y0);
        double Steps;
        double x=X0;
        double y=Y0;
        HDC HDCConsole = GetWindowDC(GetConsoleWindow());
        HPEN LineColor = CreatePen(0,1,RGB(255,0,0));
        HPEN OldPen =(HPEN)SelectObject(HDCConsole,LineColor);
    
        const double INCREMENTO = 32.0;
        if (dx >dy)
            Steps = dx;
        else
            Steps = dy;
        double Xincrement = (dx / Steps) * INCREMENTO;
        double Yincrement = (dy / Steps) * INCREMENTO;
        cout << "Xincrement: " << Xincrement<< "\n";
        int v=0;
        for(v=0; v < Steps; v++)
        {
            x = x + Xincrement;
            y = y + Yincrement;
            cout << "X: " << x  << "  Y: " << y << "\n";
            if(x>=X1 or y>=Y1) break;//porque tenho de usar esse 'if', senão dá-me mais comprimento
        }
    
        cout << v<< "\n";
        MoveToEx(HDCConsole,X0,Y0,nullptr);
        LineTo(HDCConsole,X0+100,y);
        SelectObject(HDCConsole,OldPen);
        DeleteObject(LineColor);
    }

    e como a uso:

    DrawLineAngle(100,100,0,100);

    porque o ciclo 'for' é executado 1 única vez e o 'v' é zero?
    deveria somar '32' no 'x' e 1 vez seria '132', ou seja inferior ao comprimento.... o que estou a fazer errado no código?

    • Curtir 1
  5. como usar '__attribute__((weak))'?

    #include <iostream>
    #define  event __attribute__((weak))
      
    using namespace std;
    
    class test2
    {
    public:
       void Hello() event;
        void hey()
        {
            if(&Hello==NULL) Hello();
        }
    
    };
    
    /*void test2::Hello()
    {
        cout << "hello world!!!";
    }*/
    
    test2 a;
    int main()
    {
        a.hey();
    
        return 0;
    }

    ao executar tenho 1 erro:

    "Process returned -1073741819 (0xC0000005)   execution time : 0.680 s
    Press any key to continue."

    o erro está nesta linha que estou a tentar corrigir:

    if(&Hello==NULL) Hello();

    como se usa o __attribute__((weak)) para testar se a função foi definida?

    • Curtir 1
  6. eis o meu actual código:

    void DrawRays()
    {
        int MapX =floor(PlayerPosX);
        int MapY=floor(PlayerPosY);
        while(LevelMap0[MapY][MapX]!=1)
        {
            MapX+=floor(cos(PlayerRadians)*1);
            MapY+=floor(sin(PlayerRadians)*1);
        };
        DrawLine(floor(PlayerPosX),floor(PlayerPosY),floor(MapX*32),floor(MapY*32),RGB(0,255,0));
    }

    eu somo 1 a 1 quadrado, consoante o Radiano do player, mas cada quadrado tem 32 por 32..

    alguém, no Youtube, ao mostrar 1 algoritmo DDA, disse que era o mesmo... yah.. right.

    eu posso ter o pseu-codigo errado, mas o raciocionio está correcto?

    • Curtir 1
  7. tem razão.. eu resolvi isso e muito mais.. verdade algumas classes\funções estavam repetidas e nem me tinha apercebido....

    agora tenho alguns avisos que não consigo resolver:

    1)

    hwnd = CreateWindowEx(0, classname, strCaption.c_str(),WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
                                      CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, parent, NULL, mod, this);

    tive de usar '0' para evitar 1 aviso.. e não posso usar 'NULL'.

     

    2)

    if (inst->clrBackColor==-1)

    'clrBackColor' é 1 objeto de:

    typeredef(COLORREF color);

    o '-1' é transparente... se calhar deveria outro tipo de variável.

     

    • Curtir 1
  8. como usar as opções do Linker no Code Blocks?

    eu tenho 1 class que usa o operador '='(overloading operators) e Lambdas.
    eis como compila:

    Citação

     

    "

    -------------- Clean: Debug in classcontrols (compiler: GNU GCC Compiler)---------------

    Cleaned "classcontrols - Debug"

    -------------- Build: Debug in classcontrols (compiler: GNU GCC Compiler)---------------

    g++.exe -Wall -g  -c C:\Users\Utilizador\Documents\CodeBlocks\classcontrols\main.cpp -o obj\Debug\main.o
    g++.exe  -o bin\Debug\classcontrols.exe obj\Debug\main.o  -lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32  -lgdi32 -luser32 -lkernel32 -lcomctl32 "..\..\..\..\..\Program Files\CodeBlocks\mingw32\i686-w64-mingw32\lib\libmsimg32.a" "..\..\..\..\..\Program Files\CodeBlocks\mingw32\i686-w64-mingw32\lib\libwinmm.a" "..\..\..\..\..\Program Files\CodeBlocks\mingw32\i686-w64-mingw32\lib\libgdiplus.a" "..\..\..\..\..\Program Files\CodeBlocks\mingw32\i686-w64-mingw32\lib\libgdi32.a" "C:\Program Files (x86)\CodeBlocks\MinGW\i686-w64-mingw32\lib\libbgi.a" -mwindows
    In file included from C:\Users\Utilizador\Documents\CodeBlocks\classcontrols\main.cpp:1:
    C:\Users\Utilizador\Documents\CodeBlocks\classcontrols\cambalinho.h: In static member function 'static LRESULT label::WndProcLabel(HWND, UINT, WPARAM, LPARAM)':
    C:\Users\Utilizador\Documents\CodeBlocks\classcontrols\cambalinho.h:2077:43: warning: comparison of integer expressions of different signedness: 'color' {aka 'long unsigned int'} and 'int' [-Wsign-compare]
                         if (inst->clrBackColor==-1)
                             ~~~~~~~~~~~~~~~~~~^~~~
    C:\Users\Utilizador\Documents\CodeBlocks\classcontrols\cambalinho.h: In member function 'void form::setParent(HWND)':
    C:\Users\Utilizador\Documents\CodeBlocks\classcontrols\cambalinho.h:2949:118: warning: passing NULL to non-pointer argument 1 of 'HWND__* CreateWindowExA(DWORD, LPCSTR, LPCSTR, DWORD, int, int, int, int, HWND, HMENU, HINSTANCE, LPVOID)' [-Wconversion-null]
                                       CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, parent, NULL, mod, this);
                                                                                                                          ^
    C:\Users\Utilizador\Documents\CodeBlocks\classcontrols\cambalinho.h: In static member function 'static LRESULT form::WndProcForm(HWND, UINT, WPARAM, LPARAM)':
    C:\Users\Utilizador\Documents\CodeBlocks\classcontrols\cambalinho.h:2994:24: warning: unused variable 'KeyDownCount' [-Wunused-variable]
                 static int KeyDownCount=0;
                            ^~~~~~~~~~~~
    C:\Users\Utilizador\Documents\CodeBlocks\classcontrols\main.cpp: At global scope:
    C:\Users\Utilizador\Documents\CodeBlocks\classcontrols\main.cpp:9:14: error: redefinition of 'std::__cxx11::wstring towstring(const string&)'
     std::wstring towstring(const std::string& v)
                  ^~~~~~~~~
    In file included from C:\Users\Utilizador\Documents\CodeBlocks\classcontrols\main.cpp:1:
    C:\Users\Utilizador\Documents\CodeBlocks\classcontrols\cambalinho.h:359:14: note: 'std::__cxx11::wstring towstring(const string&)' previously defined here
     std::wstring towstring(const std::string& v)"

     

    isto foi retirado do 'Build Log'. como vê tenho imensos erros, mas sei que é do compilador ou opções do Linker.

    eu criei a classe, por isso funcionou na criação, mas após reinstalar o Code Blocks, perdi tudo... ao menos tenho a classe 😉

    • Curtir 1
  9. finalmente consegui resolver, mas notei alguns erros nos links\tutorials e no youtube:
    1 - a libraria é para o CodeBlocks 32 bits, o 64 dá esse erro!!!!;

    2 - a libraria\headers são na pasta(baixei o CodeBlocks 32 bits com o compilador mingw 32 bits: 

    "C:\Program Files (x86)\CodeBlocks\MinGW\i686-w64-mingw32\include"

    e

    "C:\Program Files (x86)\CodeBlocks\MinGW\i686-w64-mingw32\lib" 

    e não na:

    "C:\Program Files (x86)\CodeBlocks\MinGW\lib"

    e não na:

    "C:\Program Files (x86)\CodeBlocks\MinGW\include"

    demorei imenso reparar nisto tudo 😞

    muito obrigado por tudo amigo.

    • Curtir 1
  10. eu uso o CodeBlocks para programar C\C++.

    queria usar o Graphics.h. eu baixei 2 ficheiros headers e a libraria... mas podem não ser os compativeis.

    adicionei a libraria e este comandos\opções do linker:

    "-lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32"

    mas, ao compilar, obtenho 1 erro: "ld.exe||cannot find -lbgi|"

    porque este erro? como o corrigir? será da compatibilidade da libraria?

    • Curtir 1
  11. eis a função para criar DIB's:

    Private Declare Function CreateDIBSection Lib "gdi32.dll" (ByVal hdc As Long, ByRef pBitmapInfo As Any, ByVal un As Long, ByRef lplpVoid As Long, ByVal handle As Long, ByVal dw As Long) As Long

    eis como uso:

    hBitmap = CreateDIBSection(hdc, bmpInfoHeader, BI_RGB, bmpPtr(0), 0, 0)

    isto funciona, mas o 'bmpPtr' não fica como ponteiro.

    como transformo o 'bmpPtr' em ponteiro e altero os valores?

    e sim o VB6 permite usar ponteiros: http://www.thevbzone.com/ em ' VB SECRETS'

  12. eis a função do RayCasting:
     

    Private Sub RayCasting()
        Dim StartAngle As Double
        Dim EndAngle As Double
        Dim IncrementAngle As Double
        Dim Distance As Double
        Dim RayX As Double
        Dim RayY As Double
        Dim RayAngle As Double
        Dim RayActualX As Double
        Dim RayActualY As Double
        Dim Wall As Integer
        Dim IncrementPixel As Double
        Dim IncrementStepSin As Double
        Dim IncrementStepCos As Double
        Dim AlturaLinha As Double
        Dim CorrecaoVisao As Double
        
        
        'Obter a posição inicial dos Raios com a posição do jogador:
        RayX = PlayerX
        RayY = PlayerY
        
        'o ângulo do meio tem de ser o ângulo do jogador
        StartAngle = PlayerAngle - DegreeToRadians(60 / 2)
        IncrementAngle = PlayerRotation / 10
        Distance = 0
        IncrementPixel = 2
        
        Dim RayCount As Long
        
        Picture1.Cls
        RayAngle = StartAngle
        For RayCount = 0 To CamWidth / 10 Step 1
            Distance = 0
            AlturaLinha = 0
            Wall = 0
            RayActualX = PlayerX
            RayActualY = PlayerY
            IncrementStepSin = Sin(RayAngle) * IncrementPixel
            IncrementStepCos = Cos(RayAngle) * IncrementPixel
            Do While (Wall = 0)
                Wall = LevelMap(Floor(RayActualY / MapResolution))(Floor(RayActualX / MapResolution))
                If (Wall <> 0) Then Exit Do
                RayActualX = RayActualX + IncrementStepCos
                RayActualY = RayActualY + IncrementStepSin
                Distance = Distance + 1
            Loop
            
            AlturaLinha = Floor(CamHalfHeight / Distance * MapResolution)
            
            DrawLine Picture1, RayCount, 0, RayCount, CamHalfHeight - AlturaLinha / 2, vbCyan
            DrawLine Picture1, RayCount, CamHalfHeight - AlturaLinha / 2, RayCount, CamHalfHeight + AlturaLinha / 2, colors(Wall)
            DrawLine Picture1, RayCount, CamHalfHeight + AlturaLinha / 2, RayCount, CamHeight, vbMagenta
            Me.Line (RayX, RayY)-(RayActualX, RayActualY), vbCyan
            
            RayAngle = RayAngle + IncrementAngle
            If (RayCount = CamWidth) Then Exit For
        Next RayCount
    End Sub

    não tenho controlo entre velocidade e tamanho da tela... a fica fica super pequena... mas não entendi como posso alterar o tamanho da tela.... só se repetir a 2ª 'Drawline" para dupla linha vertical

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

LANÇAMENTO!

eletronica2025-popup.jpg


CLIQUE AQUI E BAIXE AGORA MESMO!