如何在C++中正确引用来自不同类的类的对象?
How to correctly refer to an object of a class from a different class in C++?
我正在使用C++和SFML来制作一个自上而下的僵尸射击游戏。现在我有一个可以四处移动的玩家,他可以射击,但我正在尝试为僵尸提供一个基本的AI,他根据玩家的位置追逐玩家。
出于某种原因,僵尸正在向直线方向移动,而不是追逐玩家。我相信问题与使用不正确的玩家位置来计算僵尸的方向有关。当使用僵尸类中玩家类的位置值时,我经常得到 0 的玩家位置。
但我似乎无法弄清楚如何解决这个问题。任何帮助将不胜感激。谢谢!
这是我到目前为止的代码:
播放器.cpp
//GetPosition() is getting player position
//I even tried getting output of player's x and y position in this class and
//its correctly showing player's position
sf::Vector2f Player::GetPosition()
{
xPos = playerSprite.getPosition().x;
yPos = playerSprite.getPosition().y;
sf::Vector2f position = sf::Vector2f(xPos, yPos);
//Correctly outputs position
std::cout << "X: " << position.x << " Y: " << position.y << std::endl;
return position;
}
僵尸
#pragma once
#include <SFML/Graphics.hpp>
#include "Player.h"
class Zombie
{
public:
Zombie();
//Here I am trying to create a player object to access player position
//variable to use for Zombie direction calculations
Player p1;
Player *player = &p1;
sf::Texture zombieTexture;
sf::Sprite zombieSprite;
sf::Vector2f zombiePosition;
sf::Vector2f playerPosition;
sf::Vector2f direction;
sf::Vector2f normalizedDir;
int xPos;
int yPos;
float speed;
void Move();
};
僵尸.cpp
void Zombie::Move()
{
// Make movement
xPos = zombieSprite.getPosition().x;
yPos = zombieSprite.getPosition().y;
zombiePosition = sf::Vector2f(xPos, yPos);
playerPosition = player->GetPosition();
//Incorrectly outputs player position
//This outputs 0 constantly. But why?
std::cout << "X: " << playerPosition.x << " Y: " <<
playerPosition.y << std::endl;
direction = playerPosition - zombiePosition;
normalizedDir = direction / sqrt(pow(direction.x, 2) + pow(direction.y, 2));
speed = 2;
//Rotate the Zombie relative to player position
const float PI = 3.14159265;
float dx = zombiePosition.x - playerPosition.x;
float dy = zombiePosition.y - playerPosition.y;
float rotation = (atan2(dy, dx)) * 180 / PI;
zombieSprite.setRotation(rotation + 45);
sf::Vector2f currentSpeed = normalizedDir * speed;
zombieSprite.move(currentSpeed);
}
僵尸怎么知道要追哪个玩家?在你的Zombie
类中,你有一个成员p1
它永远不会被移动,player
总是指向它。可能你需要的是一个函数
void Zombie::chasePlayer(Player* p)
{
player = p;
}
然后在 Main 中.cpp添加一行
zombie.chasePlayer(&player);
更一般地说,您可能想检查哪个是最近的玩家并追逐那个。
相关文章:
- 如何在C++中正确引用来自不同类的类的对象?
- C 指针和对象作为不同类的一部分
- 需要实例化不同类/对象并在启动时确定的硬件插槽的设计模式
- 如何生成派生同类对象的类
- 使用转换运算符相互转换两个不同类的对象
- 不同类对象的数组
- (C++) 指向不同类中对象的指针的指针
- 计算不同类的对象数量
- 不同类别的 2 个对象之间的信号/插槽
- 分配不同类中的对象的值
- 未定义的引用:试图初始化来自不同类的对象的指针数组
- 类函数可以具有不同类对象的参数
- 在不同类的对象之间共享变量 (C++)
- 如何将具有不同类(但相同基础)的对象存储在一个变量中
- 如何比较两个不同类的对象
- 分配不同类对象时出现赋值错误
- 读取包含2个不同类的对象的数据文件
- 指向从 1 个基类继承的不同类对象的指针数组
- C++:如何让函数接受来自任何命名空间的具有相同类名的对象
- 尝试创建不同类对象的单个数组