朝着玩家的方向移动玩家?使用变换矩阵

时间:2018-11-27 18:15:05

标签: c++ math visual-studio-2017

我在3D空间中有两个字符。我希望敌人朝玩家前进。 我刚刚完成一个函数,该函数接受两个对象的变换,并返回一个矩阵,然后将其应用于我的敌人(覆盖位置部分),结果他一直在看玩家。我不知道该如何让他朝那个方向前进。

1 个答案:

答案 0 :(得分:0)

我假设每个字符都有一个位置,因此您应该能够添加运算符来进行P1 - P2以获得3D矢量差异。这样,只需将矢量长度标准化为字符速度即可。这样会进行模拟,敌人会朝玩家跑去,而玩家会试图逃跑,但速度较慢,所以敌人最终会抓住玩家。

#include <iostream>
#include <cmath>

struct Position {
    double x;
    double y;
    double z;
    Position& operator+=(const Position& other) {
        x += other.x;
        y += other.y;
        z += other.z;
        return *this;
    }
    Position operator+(const Position& other) const {
        Position rv(*this);
        rv += other;
        return rv;
    }
    Position& operator-=(const Position& other) {
        x -= other.x;
        y -= other.y;
        z -= other.z;
        return *this;
    }
    Position operator-(const Position& other) const {
        Position rv(*this);
        rv -= other;
        return rv;
    }
    Position operator-() const {
        Position rv(*this);
        rv.x = -rv.x;
        rv.y = -rv.y;
        rv.z = -rv.z;
        return rv;
    }
    Position& operator*=(double f) {
        x *= f;
        y *= f;
        z *= f;
        return *this;
    }
    double length() const {
        return std::sqrt(x*x + y*y + z*z);
    }
    void normalize(double max_speed) {
        double len=length();
        if(len>max_speed) {
            *this *= max_speed/len;
        }
    }
    friend std::ostream& operator<<(std::ostream&, const Position&);
};
std::ostream& operator<<(std::ostream& os, const Position& pos) {
    os << "{" << pos.x << "," << pos.y << "," << pos.z << "}";
    return os;
}

int main() {
    Position enemy{100, 100, 100};
    Position player{50, 150, 20};
    Position enemy_aim;
    Position player_flee;

    while( (enemy_aim = player-enemy).length()>0 ) {
        std::cout << "distance: " << enemy_aim.length() << "\n";
        std::cout << "enemy: " << enemy << "  player: " << player << "\n";

        player_flee = enemy_aim;    // player runs in the same direction (to get away)
        player_flee.normalize(5);   // the max speed of the player is 5
        player += player_flee;      // do the players move

        enemy_aim = player-enemy;   // recalc after players move
        enemy_aim.normalize(10);    // the max speed of the enemy is 10
        enemy += enemy_aim;         // do the enemys move
    }
    std::cout << "enemy: " << enemy << "  player: " << player << "\n";
}