如何旋转一个物体使其面向另一个物体?
How to rotate an object so it faces another?
我正在用 opengl 制作游戏,但我不知道如何让我的敌人角色转身面对我的玩家。我只需要敌人在 y 轴上朝向玩家旋转。然后我希望他们转向 him.I 已经尝试了很多不同的方法,但没有任何效果。
您需要在项目开始时自行决定一些要在整个项目中使用的事项,例如位置和方向的表示(以及 screen/clip飞机等)但是,你没有提到任何这些。所以您可能需要调整下面的代码以适应您的游戏,但它应该很容易适应和适用。
对于以下示例,我假设 -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
}
使用上面的代码,您应该能够移动您的播放器对象并设置旋转角度(您需要注意返回和预期角度值的 radians/degrees)。
我正在用 opengl 制作游戏,但我不知道如何让我的敌人角色转身面对我的玩家。我只需要敌人在 y 轴上朝向玩家旋转。然后我希望他们转向 him.I 已经尝试了很多不同的方法,但没有任何效果。
您需要在项目开始时自行决定一些要在整个项目中使用的事项,例如位置和方向的表示(以及 screen/clip飞机等)但是,你没有提到任何这些。所以您可能需要调整下面的代码以适应您的游戏,但它应该很容易适应和适用。
对于以下示例,我假设 -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
}
使用上面的代码,您应该能够移动您的播放器对象并设置旋转角度(您需要注意返回和预期角度值的 radians/degrees)。