please assist me on how do I achieve a simple teleportation of a sprite. I simply want the sprite to translate to the right of the screen if it exit the left of the screen and vise versa. Example image below..(Sample game like pacman, able to teleport from one door to another)
I just want to keep it simple. Don't need difficult algorithm. Just translate the sprite to the same y-axis if the sprite enter left at the same y-axis. Here is what I have tried.
void Physics::Boundary(float PosX, float PosY)
{
this->PosX = PosX;
this->PosY = PosY;
if (this->PosX >= 638.0f)
{
this->PosX = 2.0f;
this->PosY = PosY;
}
if (this->PosX <= 2.0f)
{
this->PosX = 638.0f;
this->PosY = PosY;
}
if (this->PosY >= 638.0f)
{
this->PosX = PosX;
this->PosY = 2.0f;
}
if (this->PosY <= 2.0f)
{
this->PosX = PosX;
this->PosY = 638.0f;
}
}
If you look at the first if-statement of your code, it sets the PosX
field to 2.0f
. However, the next if-statement is checking for PosX <= 2.0f
. This will always be true because in the first if-statement you set it to 2.0f
. In your case you will always be "teleported" back to the original position (638.0f
). You can try using an if-else statement instead:
void Physics::Boundary(float PosX, float PosY)
{
this->PosX = PosX;
this->PosY = PosY;
if (this->PosX >= 638.0f)
{
this->PosX = 2.0f;
this->PosY = PosY;
}
else if (this->PosX <= 2.0f)
{
this->PosX = 638.0f;
this->PosY = PosY;
}
if (this->PosY >= 638.0f)
{
this->PosX = PosX;
this->PosY = 2.0f;
}
else if (this->PosY <= 2.0f)
{
this->PosX = PosX;
this->PosY = 638.0f;
}
}
You could also just check less-than 2.0f instead of less-than or equals 2.0f.