如何在 C++ 中从不同的 class 正确引用 class 的对象?

How to correctly refer to an object of a class from a different class in C++?

我正在使用 C++ 和 SFML 制作自上而下的僵尸射击游戏。现在我有一个可以四处移动并可以射击的玩家,但我正在尝试为根据玩家位置追逐玩家的僵尸提供一个基本的 AI。

出于某种原因,僵尸正在直线移动而不是追逐玩家。我认为问题与用于计算僵尸方向的玩家位置不正确有关。在僵尸 class 中使用来自玩家 class 的位置值时,我的玩家位置不断得到 0。

但我似乎不知道如何解决这个问题。任何帮助将不胜感激。谢谢!

到目前为止,这是我的代码:

Player.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;
}

Zombie.h

#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();

};

Zombie.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 class 中,您有一个从未移动过的成员 p1,并且 player 始终指向该成员。可能你需要的是一个函数

void Zombie::chasePlayer(Player* p)
{
   player = p;
}

然后在main.cpp中添加一行

zombie.chasePlayer(&player);

更一般地说,您可能喜欢检查哪个是最近的玩家并追逐那个。