c++ - 如何从 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);
}
解决方案
僵尸怎么知道要追哪个玩家?在您的Zombie
班级中,您有一个p1
永远不会移动并player
始终指向它的成员。可能你需要的是一个功能
void Zombie::chasePlayer(Player* p)
{
player = p;
}
然后在 main.cpp 添加一行
zombie.chasePlayer(&player);
更一般地,您可能希望例如检查哪个是最近的玩家并追逐那个玩家。
推荐阅读
- git - 重置我的最后一次提交撤消许多提交
- python - 如何重新调整 fft 点以获得与解析解相同的结果?
- javascript - 时刻js更改日期时间的日期部分
- sqlite - 如何计算表中的时间差 HH:MM?
- javascript - 显示表格内的数据
- python - 检查列表的任何字符串是否出现在更大的字符串上
- batch-file - 将所有单词连接到批处理中的同一行后如何在单词之间保留空格
- python - 使用 zip() 函数时如何解决以下错误?TypeError:“列表”对象不可调用
- azure - 托管身份 - 是否节省证书成本?
- c# - 将 Windows 标识名称传递给服务器