将玩家朝其面向的方向移动?使用变换矩阵[关闭]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将玩家朝其面向的方向移动?使用变换矩阵[关闭]相关的知识,希望对你有一定的参考价值。
我在3d空间中有两个字符。我希望敌人向玩家移动。我刚刚完成了一个函数,它接受了两个对象的变换,并返回一个矩阵,然后我将其应用于我的敌人(覆盖位置部分),结果他总是看着玩家。我无法弄清楚我怎么能让他朝这个方向前进。
答案
我假设每个角色都有一个位置,所以你应该能够添加运算符来做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() << "
";
std::cout << "enemy: " << enemy << " player: " << player << "
";
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 << "
";
}
以上是关于将玩家朝其面向的方向移动?使用变换矩阵[关闭]的主要内容,如果未能解决你的问题,请参考以下文章