ytn2001 发表于 2023-7-11 21:55:30

C++ FPS游戏坐标转屏幕坐标的类库源码



C++ FPS游戏坐标转屏幕坐标的类库源码

这份代码矩阵部分是4x4矩阵的,如果你的游戏人物矩阵不是4x4的就自己改一下那里的代码就能用了。

#pragma once
#include <windows.h>

typedef struct _WORD_LOCATION_
{
    float x;
    float y;
    float z;
}WORD_LOCATION;

typedef struct _CUT_COOR_
{
    float x;
    float y;
    float z;
    float w;
}CUT_COOR;

typedef struct _NDC_COOR_
{
    float x;
    float y;
    float z;
}NDC_COOR;

typedef struct _SCREEN_COOR_
{
    float x;
    float y;
}SCREEN_COOR;

typedef struct _SCREEN_PARAM_
{
    float height;
    float width;
}SCREEN_PARAM;

class World2Screen
{
public:
    float PersonMatrix;
    WORD_LOCATION WordLocation;
    CUT_COOR CutCoor;
    NDC_COOR NDCCoor;
    SCREEN_COOR ScreenCoor;
    SCREEN_PARAM ScreenParam;
public:
    World2Screen(WORD_LOCATION Word, float* PersonMatrix);
    void Word2CutCoor();
    bool InVisualField();
    void Cut2NDCCoor();
    void NDC2ScreenCoor();

};


#include "World2Screen.h"

World2Screen::World2Screen(WORD_LOCATION Word, float* PersonMatrix)
{
    this->WordLocation.x = Word.x;
    this->WordLocation.y = Word.y;
    this->WordLocation.z = Word.z;
    memcpy_s(this->PersonMatrix,sizeof(this->PersonMatrix),PersonMatrix,sizeof(this->PersonMatrix));
}

void World2Screen::Word2CutCoor()
{   
    this->CutCoor.x = this->PersonMatrix * this->WordLocation.x + this->PersonMatrix * this->WordLocation.y + this->PersonMatrix * this->WordLocation.z + this->PersonMatrix;
    this->CutCoor.y = this->PersonMatrix * this->WordLocation.x + this->PersonMatrix * this->WordLocation.y + this->PersonMatrix * this->WordLocation.z + this->PersonMatrix;
    this->CutCoor.z = this->PersonMatrix * this->WordLocation.x + this->PersonMatrix * this->WordLocation.y + this->PersonMatrix * this->WordLocation.z + this->PersonMatrix;
    this->CutCoor.w = this->PersonMatrix * this->WordLocation.x + this->PersonMatrix * this->WordLocation.y + this->PersonMatrix * this->WordLocation.z + this->PersonMatrix;
}

bool World2Screen::InVisualField()
{
    if (this->CutCoor.w < 0.01) { return false; };
}

void World2Screen::Cut2NDCCoor()
{
    this->NDCCoor.x = this->CutCoor.x / this->CutCoor.w;
    this->NDCCoor.y = this->CutCoor.y / this->CutCoor.w;
    this->NDCCoor.z = this->CutCoor.z / this->CutCoor.w;
}

void World2Screen::NDC2ScreenCoor()
{
    this->ScreenCoor.x = this->ScreenParam.width / 2 + (this->ScreenParam.width / 2) * this->NDCCoor.x;
    this->ScreenCoor.y = this->ScreenParam.height / 2 - (this->ScreenParam.height / 2) * this->NDCCoor.y;
}

页: [1]
查看完整版本: C++ FPS游戏坐标转屏幕坐标的类库源码