SFML community forums
Help => General => Topic started by: servvs on April 11, 2010, 09:24:40 pm
-
Ok so I have a ship sprite that I want to bounce back and forth from each edge of the screen. I am having trouble with it and here is the code:
float enemyVelocity = 150.0f * ElapsedTime;
float enemyXMax = wWidth - Sprite2.GetScale().x;
float enemyXMin = 0 + Sprite2.GetScale().x;
float spriteWidth = Sprite2.GetScale().x;
float spriteX;
spriteX = Sprite2.GetPosition().x;
cout << spriteX << endl;
if (spriteX >= enemyXMax)
{
enemyVelocity = enemyVelocity * -1;
spriteX = enemyXMax;
}
else if (spriteX <= enemyXMin);
{
enemyVelocity = enemyVelocity * -1;
spriteX = enemyXMin;
}
Sprite2.Move(enemyVelocity, 0);
-
Really no help? :(
-
What is your problem? :D
-
Ok so we have all heard of the game alien invaders, where the enemy ships bounce back and forth and you shoot them with your space ship right? Well right now I am having trouble getting them to bounce back and forth. I have updated the code and tried it at a different view, but I still get the same thing. Basically instead of bouncing off of the screen and to the other side it bounces between the edge and the first pixel of the edge causing it to vibrate and be stuck.... I can't get it it to just bounce and go the other direction... Here is my updated code
int x = wWidth/2;
int x_velocity = 200 * ElapsedTime;
if (x <= 0)
x_velocity = -x_velocity;
if (x >= wWidth)
x_velocity = -x_velocity;
x += x_velocity;
Sprite2.SetPosition(x, y);
-
Basically instead of bouncing off of the screen and to the other side it bounces between the edge and the first pixel of the edge causing it to vibrate and be stuck....
I remember of this annoying problem when I was young and started programming games :lol:
Have a look at the pong demo that comes with SFML, it has a ball that bounces on edges and paddles. Look at this excerpt:
if (ball.GetPosition().y < 0.f)
{
ballSound.Play();
ballAngle = -ballAngle;
ball.SetY(0.1f);
}
if (ball.GetPosition().y + ball.GetSize().y > window.GetView().GetSize().y)
{
ballSound.Play();
ballAngle = -ballAngle;
ball.SetY(window.GetView().GetSize().y - ball.GetSize().y - 0.1f);
}
As you see, the trick here is to move the ball a little bit back when it bounces, so that you make sure that the collision condition won't be triggered again on the next frame. If it wasn't there, the ball would change direction, but it's probably still outside of the screen so the same condition is triggered and the direction is changed indefinitely, making the annoying vibration effect.
-
I tested it out but still can't get it to work correctly. Here is the entire source at pastebin (not very big source)
http://pastebin.com/HfvAhSfn
-
Okie dokie then, got it working with a little but of umm... work. http://pastebin.com/gmcShYyB for the updated code that works how it should. Now to create missles and collision and then to separate everything into classes :D