首页 > 解决方案 > 如何从 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;
}

僵尸.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();

};

僵尸.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);
}

标签: c++sfml

解决方案


僵尸怎么知道要追哪个玩家?在您的Zombie班级中,您有一个p1永远不会移动并player始终指向它的成员。可能你需要的是一个功能

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

然后在 main.cpp 添加一行

zombie.chasePlayer(&player);

更一般地,您可能希望例如检查哪个是最近的玩家并追逐那个玩家。


推荐阅读