Ответ в теме: Анимация объекта

SFML и C++ Уроки \ Разработка игр Форумы SFML Graphics Анимация объекта Ответ в теме: Анимация объекта

#4430
Alex_Ken
Alex_Ken
Участник
Сообщений:11

Зарегистрирован:
07.01.2017

Репутация:0

#include <SFML/Graphics.hpp>
using namespace sf;
class Entity
{
public:
float dx, dy, x, y, speed;
int h, w, health;
bool onGround;
String name;
Image image;
Texture texture;
Sprite sprite;
Entity(Image &image, String Name, float X, float Y, int W, int H)
{
health = 100; onGround = false; speed = 0; x = X; y = Y; w = W; h = H; name = Name; dx = 0; dy = 0;
texture.loadFromImage(image);
sprite.setTexture(texture);
//sprite.setOrigin(w/2, h/2);
}
};

class Player :public Entity
{
public:
float CF = 0;
float time;
enum {right, left, jump, down, stay} state;
Player(Image &image, String Name, float X, float Y, int W, int H) :Entity(image, Name, X, Y, W, H)
{
state = stay;
if (name == “Player1″){
sprite.setTextureRect(IntRect(0, 0, w, h));
}
}

void control()
{
time = time / 800;
if (Keyboard::isKeyPressed)
{
if (Keyboard::isKeyPressed(Keyboard::Right))
{
state = right; speed = 0.1;
CF += 0.005*time;
if (CF > 6) CF -= 6;
sprite.setTextureRect(IntRect(36 * int(CF), 48, 30, 48));
}
if (Keyboard::isKeyPressed(Keyboard::Left))
{
state = left; speed = 0.1;
CF += 0.005*time;
if (CF > 6) CF -= 6;
sprite.setTextureRect(IntRect(36 * int(CF), 48, -30, 48));
}
}
}

void update(float time)
{
control();
switch (state)
{
case right: dx = speed; break;
case left: dx = -speed; break;
}
x+=dx*time;
y+=dy*time;
speed = 0;
sprite.setPosition(x+w/2,y+h/2);
}
};

int main()
{
RenderWindow window(VideoMode(640, 480), “Donald Duck”);

Clock clock;

Image duck;
duck.loadFromFile(“images/duck.png”);

Player p(duck, “Player1″, 200, 200, 27.0, 48.0);

while (window.isOpen())
{
float time = clock.getElapsedTime().asMicroseconds();
clock.restart();
time = time / 800;

Event event;
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
window.close();
}

p.update(time);
window.clear();
window.draw(p.sprite);
window.display();
}
return 0;
}