Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: getPosition not getting updated in other class  (Read 1999 times)

0 Members and 1 Guest are viewing this topic.

PatrixOK

  • Newbie
  • *
  • Posts: 1
    • View Profile
    • Email
getPosition not getting updated in other class
« on: March 15, 2021, 12:26:57 pm »
Hello,

i need to create bullet object based on player position.

I have 2 classes, Bullet and Player and i want to copy player.getPosition() to bullet.setPosition()

Problem is that player.getPosition() is not updating when moving, it have only value that was initiated when Player object is created.


Bullet class:
Quote
#include "Bullet.h"
#include "Player.h"
Bullet a;
Bullet::Bullet(float t_Width, float t_High)
{
   
   shape.setFillColor(Color(237, 9, 9));
   shape.setSize({ t_Width, t_High });
   shape.setOrigin(t_Width / 2.f, t_High / 2.f);
   
}



void Bullet::update()
{
   getPlayerPosition();
   

   if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
   {
      
      shape.move(velocity);
      shape.setPosition(getPlayerPosition().x,getPlayerPosition().y);

   }

}

Vector2f Bullet::getPlayerPosition()
{
   return a.PlayerPosition();
}
[/quote]

Quote
Player:

Vector2f Player::PlayerPosition()
{
   return shape.getPosition();
}


Can someone help? Thanks in advance!

« Last Edit: March 15, 2021, 12:44:36 pm by PatrixOK »

kojack

  • Sr. Member
  • ****
  • Posts: 343
  • C++/C# game dev teacher.
    • View Profile
Re: getPosition not getting updated in other class
« Reply #1 on: March 20, 2021, 08:43:53 am »
In your Bullet::getPlayerPosition() function you are doing return a.PlayerPosition();
But a is a Bullet that was created at the top of the file. Bullets don't have a PlayerPosition() function (or if they do, we can't see that part of the code).
I'm guessing that's a typo when posting this to the forum and it would really be Player a; at the top.

But that would be a problem too, since that would be a player that only the Bullet file knows about, not the player that the rest of the game knows.
So when the player moves, the second player stored in the variable a doesn't.

What should fix it is if you make sure Bullet::getPlayerPosition() is referring to the actual main player object, not a local second player object.

 

anything