如何旋转一个对象使其面向另一个对象
How to rotate an object so it faces another?
我正在用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
}
使用上面的代码,你应该能够移动你的玩家对象并设置旋转角度(你需要注意返回和预期角度值的弧度/度)。
相关文章:
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 从多个源构造一个对象,包括一个对象向量
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 检查哪个对象调用了另一个对象的对象方法
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 包装一个对象并假装它是一个 int
- 形状对象的旋转和缩放不正确C++
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 如何在qt中将信号和插槽与另一个对象连接 --解决了
- 如何使用函数将一个对象的输入复制到另一个对象中
- 如何将对象围绕另一个对象(C 和OGRE3D)旋转
- 围绕另一个对象旋转对象
- 旋转一个对象面对另一个C
- 围绕另一个对象旋转的物体不断加速
- 在 C++/OpenGL 中围绕另一个对象旋转投影一个对象
- 创建一个围绕对象 OpenGL C++旋转的相机
- 如何旋转一个对象使其面向另一个对象