我正在使用C ++和SFML制作自上而下的僵尸射击游戏。现在,我有一个可以移动的可以射击的球员,但是我正在尝试为僵尸提供基本的AI,该僵尸可以根据玩家的位置追逐该玩家。
由于某种原因,僵尸在直线移动,而不是追逐玩家。我认为问题与用于计算僵尸方向的错误玩家位置有关。在僵尸类中使用玩家类的位置值时,我的玩家位置始终为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);
}
答案 0 :(得分:0)
僵尸如何知道要追逐哪个玩家?在您的Zombie
类中,您有一个成员p1
,该成员从未移动过,player
始终指向该成员。可能您需要的是功能
void Zombie::chasePlayer(Player* p)
{
player = p;
}
然后在main.cpp中添加一行
zombie.chasePlayer(&player);
更一般而言,您可能希望检查哪个是最接近的玩家,然后追逐那个玩家。