如何在C++中正确引用来自不同类的类的对象?

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

本文关键字:同类 对象 引用 C++      更新时间:2023-10-16

我正在使用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);

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