我正在使用opengl进行游戏,我无法弄清楚如何让我的敌人角色转向面对我的玩家。我只需要敌人在y轴上向玩家旋转。然后我希望他们走向他。我已经尝试了一些不同的方法但是还没有能够得到任何工作。
答案 0 :(得分:2)
在整个项目开始时,您需要在项目开始时自行决定一些事项,例如位置和方向的表示(以及屏幕/剪裁平面的设置等)但是,你没有提到任何这个。所以你可能需要调整下面的代码以适应你的游戏,但它应该很容易适应和适用。
对于以下示例,我假设-y轴是屏幕的顶部。
#include <math.h> // atan2
// you need to way to represent position and directions
struct vector2{
float x;
float y;
} playerPosition, enemyPosition;
float playerRotation;
// setup the instances and values
void setup() {
// Set some default values for the positions
playerPosition.x = 100;
playerPosition.y = 100;
enemyPosition.x = 200;
enemyPosition.y = 300;
}
// called every frame
void update(float delta){
// get the direction vector between the player and the enemy. We can then use this to both calculate the rotation angle between the two as well as move the player towards the enemy.
vector2 dirToEnemy;
dirToEnemy.x = playerPosition.x - enemyPosition.x;
dirToEnemy.y = playerPosition.y - enemyPosition.y;
// move the player towards the enemy
playerPosition.x += dirToEnemy.x * delta * MOVEMENT_SPEED;
playerPosition.y += dirToEnemy.y * delta * MOVEMENT_SPEED;
// get the player angle on the y axis
playerRotation = atan2(-dirToEnemy.y, dirToEnemy.x);
}
void draw(){
// use the playerPosition and playerAngle to render the player
}
使用上面的代码,您应该能够移动玩家对象并设置旋转角度(您需要注意返回和预期角度值的弧度/度数)。