新DirectX,自定义类破碎

New to DirectX, custom class broken

本文关键字:破碎 自定义 DirectX      更新时间:2023-10-16

我是栈溢出的新手,虽然我已经写了几年的基本和中级c++程序,但我从来没有能够超越它。我最近学习了如何通过一个框架在DirectX中工作,这个框架是我从www.planetchili.net得到的。我正尝试着为编程课程开发一些类似于《小行星》类型的游戏,并展示AI和寻径功能。玩家将与其他三角形飞船进行狗斗,而不是炸毁小行星。

该框架附带了一个游戏对象,通过它我一直在做我的大部分工作。然而,我意识到我可能应该为Ship编写自己的类,它将包含执行Ship相关操作所需的变量,如绘制船和跟踪位置和分数等统计数据。

然而,我遇到了一个问题,似乎像一个inception级的悖论。该框架使用了D3Dgraphics,它声明并使用了一个名为gfx的D3D对象。为了利用Ship中的D3D绘图功能,我在Ship.h中加入了D3D库并创建了一个D3D对象。

我可以在游戏中声明和实例化Ship对象,但是直接在游戏中使用的绘图功能在通过Ship对象使用时不起作用。我不知道为什么会这样,但我相信这可能是因为我编织的这张恶心的网。Game对象使用一个D3D对象,该对象拥有一个名为Go()的函数,似乎可以绘制和破坏框架,Ship对象使用一个D3D对象,但无法访问Game的Go()方法,然后Game使用Ship。

这是我的一小段代码…请帮我澄清一下。

Ship.cpp
    //Ship.cpp
    #include "Ship.h"
    #include <math.h>
    enter code here
    //Constructor
    Ship::Ship(HWND hWnd)
    :   gfx ( hWnd )
    {}
    void Ship::drawLine(int x1, int x2, int y1, int y2){
    //Draws a line using gfx.putPixel- This function works perfectly if declared and used directly in Game.cpp
    }
Ship.h
    //Ship.h
    #pragma once
    #include "D3DGraphics.h"
    #include "Keyboard.h"
    #include <vector>
    class Ship{
    private:
        D3DGraphics gfx;
    public:
        Ship::Ship(HWND hWnd); //Default Constructor
    };


 //Game.h
    #pragma once
    #include "Ship.h"
    #include "D3DGraphics.h"
    #include "Keyboard.h"
    class Game
    {
    public:
        Game( HWND hWnd,const KeyboardServer& kServer );
        void Go();
        //Member functions
    private:
        void ComposeFrame();
    private:
        D3DGraphics gfx;
        KeyboardClient kbd;
        Ship psp;
    };
//Game.cpp
#include "Game.h"
#include <math.h>
Game::Game( HWND hWnd,const KeyboardServer& kServer )
:   gfx ( hWnd ),
    psp(hWnd),
    kbd( kServer )
{}
void Game::Go()
{
    gfx.BeginFrame();
    ComposeFrame();
    gfx.EndFrame();
}
void Game::ComposeFrame()
{
    psp.drawShip();
}

您的Game类正在使用的D3DGraphics对象与Ship D3DGraphics对象在内存中不同。你必须使用指针来确保你画的是同一个对象,把它改成这些片段:

    class Ship{
        private:
            D3DGraphics *gfx;
        public:
            Ship::Ship(D3DGraphics *pGfx); //Default Constructor
        };

//Constructor
        Ship::Ship(D3DGraphics *pGfx)
        {
            gfx = pGfx;    
        }

Game::Game( HWND hWnd,const KeyboardServer& kServer )
:   gfx ( hWnd ),
    psp(gfx),
    kbd( kServer )
{}

而不是使用gfx.你现在必须使用gfx->在你的Ship类。即用gfx->PutPixel()代替gfx.PutPixel()

一个小边注,尝试改变你的变量名称,以提供更多的信息使用常用的匈牙利符号:http://en.wikipedia.org/wiki/Hungarian_notation