Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SFML/Graphics.hpp>
- #include <SFML/System.hpp>
- #include <cmath>
- #include "player.h"
- class Player{
- private:
- sf::RenderWindow& window;
- sf::Texture playerTexture;
- sf::Sprite playerSprite;
- public:
- float x = 0, y = 0;
- float velocityX = 0, velocityY = 0;
- float currentVelocity = 0;
- float maxVelocity = 8;
- //functions
- Player(sf::RenderWindow& w, int x, int y): window(w)
- {
- this->x = x;
- this->y = y;
- this->playerTexture.loadFromFile("Sprites/ship.png");
- this->playerSprite.setTexture(playerTexture);
- this->playerSprite.setPosition(this->x,this->y);
- this->playerSprite.setOrigin(this->playerSprite.getLocalBounds().width / 2, this->playerSprite.getLocalBounds().height / 2);
- }
- ~Player(){
- }
- void AddXVelocity(float v){
- velocityX += v;
- };
- void AddYVelocity(float v){
- velocityY += v;
- };
- void NormalizeVelocity(){
- currentVelocity = fabs(velocityX) + fabs(velocityY);
- if(currentVelocity > maxVelocity){
- //percentage that each axis is the of the total velocity
- int xp = fabs(velocityX) / (fabs(velocityX) + fabs(velocityY));
- int yp = fabs(velocityY) / (fabs(velocityX) + fabs(velocityY));
- //different normalization if value is negative
- if(velocityX > 0){
- velocityX = maxVelocity * xp;
- }
- else if(velocityX < 0){
- velocityX = -maxVelocity * xp;
- }
- if(velocityY < 0){
- velocityY = -maxVelocity * yp;
- }
- else if(velocityY > 0){
- velocityY = maxVelocity * yp;
- }
- }
- x += velocityX;
- y -= velocityY;
- }
- void GetInput(){
- //get keyboard input
- if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)){
- AddYVelocity(.1);
- }
- if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)){
- AddYVelocity(-.1);
- }
- if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)){
- AddXVelocity(-.1);
- }
- if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)){
- AddXVelocity(.1);
- }
- }
- void DrawPlayer(){
- window.draw(playerSprite);
- }
- void LookAtMouse(){
- //get mouse coords
- sf::Vector2f mouseCoords;
- mouseCoords = window.mapPixelToCoords(sf::Mouse::getPosition(window));
- int mouseX = mouseCoords.x;
- int mouseY = mouseCoords.y;
- //keep the player looking at the mouse
- float dx = mouseX - x;
- float dy = mouseY - y;
- float rotation = (atan2(dy, dx) * 180 / 3.14159265);
- playerSprite.setRotation(rotation + 90);
- }
- void Update(){
- GetInput();
- NormalizeVelocity();
- LookAtMouse();
- playerSprite.setPosition(x,y);
- DrawPlayer();
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement