如何旋转一个对象使其面向另一个对象

How to rotate an object so it faces another?

本文关键字:一个对象 何旋转 旋转      更新时间:2023-10-16

我正在用opengl制作一个游戏,我不知道如何让我的敌人角色转向面对我的玩家。我只需要敌人在y轴上向玩家旋转。然后我希望他们向他靠近。我尝试了很多不同的方法,但都没能奏效。

在项目开始时,您需要自己决定一些事情,以便在整个项目中使用,比如位置和方向的表示(以及屏幕/剪辑平面的设置等)。然而,您还没有提到这些。因此,你可能需要调整下面的代码以适应你的游戏,但它应该很容易适应和适用。

对于下面的例子,我假设-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
}

使用上面的代码,你应该能够移动你的玩家对象并设置旋转角度(你需要注意返回和预期角度值的弧度/度)。