(SFML)按下键时,播放器构造函数未使用正确的动画进行更新



当按下正确的相应键时,我的子画面会向左、向右、向上和向下移动,但只使用第 0 行动画,但由于某种奇怪的原因,当我同时按下两个键时,例如 (W,A( 或 (S, D( 被转移到相反的动画它正在移动到哪一边。我尝试将引导动画更新的 if 语句移动到按键 if 语句内的嵌套 if 语句,但这没有任何好处,然后我尝试仅根据按键更新它,没有嵌套的 if 语句,这也不起作用......我是 SFML 的新手,所以弄清楚这一点真的很伤我的头,我也不介意批评,如果您看到我在精灵运动方面可以做得更好的东西,请告诉我!感谢您的帮助。

下面是我的播放器类构造函数

#include "Player.h"


Player::Player(Texture* texture, Vector2u imageCount, float switchTime, float speed) :
// initializer list from animation.cpp
animation(texture, imageCount, switchTime) 
{
this->speed = speed;
row = 0;

body.setSize(Vector2f(100.0f, 150.0f));
body.setTexture(texture);
//sets initial position for test sprite sheet
body.setPosition(550.0f, 900.0f);
}

Player::~Player()
{
}

void Player::Update(float deltaTime)
{
Vector2f movement(0.0f, 0.0f);

if (Keyboard::isKeyPressed(Keyboard::A))
{
//if A is pressed move to the left on the  x axis
movement.x -= speed * deltaTime;
}
if (Keyboard::isKeyPressed(Keyboard::D))
{
//if D is pressed move to the right on the x axis
movement.x += speed * deltaTime;
}
if (Keyboard::isKeyPressed(Keyboard::W))
{
// if W is pressed move up on the y axis
movement.y += speed * deltaTime;
}
if (Keyboard::isKeyPressed(Keyboard::S))
{
// if S is pressed move down on the y axis
movement.y -= speed * deltaTime;
}

if (movement.x == 0.0f || movement.y == 0.0f)//for idle animation
{
row = 0;//idle row for now just using walking until I get idle animation
}
else if(movement.x > 0.0f)
{
row = 1; //walking to the left animation
}
else if (movement.x < 0.0f )
{
row = 3; //walking to the right animation
}
else if (movement.y > 0.0f)
{
row = 0; // walking to stright animation
}
else if (movement.y < 0.0f)
{
row = 2;// walking back animation
}

animation.Update(row, deltaTime);
body.setTextureRect(animation.uvRect);
body.move(movement);

}
void Player::Draw(RenderWindow& window)
{
window.draw(body);
}

下面是我的播放器类初始化

#pragma once
#include <SFML/Graphics.hpp>
#include "Animation.h"
using namespace std;
using namespace sf;
class Player
{
public:
Player(Texture* texture, Vector2u imageCount, float switchTime, float speed);
~Player();
void Update(float deltaTime);
void Draw(RenderWindow& window);
private:
RectangleShape body;
Animation animation;
unsigned int row;
float speed;
};

在游戏下方循环和播放器函数调用

Player player(&playerTexture, Vector2u(9, 4), 0.09f, 100.0);
//*************************************************************
//clock & Time
float deltaTime = 0.0f;
Clock clock;

while (window.isOpen())
{
deltaTime = clock.restart().asSeconds();
//*********************************************************
//Player Input
if (Keyboard::isKeyPressed(Keyboard::Escape))
{
window.close();
}

//**********************************************************
//draws everything
player.Update(deltaTime);
window.clear();
window.draw(spritestartingBG);
player.Draw(window);
window.display();
}
return 0;
}

除非沿对角线移动,否则if (movement.x == 0.0f || movement.y == 0.0f)将为真 - 您可能希望 || 为 &&。

同样,您的左/右动画是相反的 - 当 movement.x <0.0 而不是> 0.0 时,您正在向左移动。

最新更新