How to make an Smooth Movement in C++, SFML - c++

I have a problem doing an smooth movement in c++ w/ sfml.
Someone can make an algorithm to smooth move a shape / sprite by 15 px (the sprite / shape is 15 px) by pressing a button? Thanks.

Because many other programmers might want to know that, here it is, but next time ask a more precise question
Here's my way to make a smooth movement:
Take your initial movement, lets say 25, 15 per second
Make a loop like this:
void GameEngine::GameLoop()
{
sf::Clock timer;
sf::Time tickRate;
sf::Vector2f movement(25.0,15.0); // Your movement vector
while(/* wahtever */){
tickRate = timer.restart();
yourShape.move(movement * ((float)tickRate.asMilliseconds() / 1000)); //Move your shape depending on the time elapsed between two frame
yourWindow.clear();
yourWindow.draw(yourShape);
yourWindow.display();
}
}

Related

SFML sf::View::move inconstancy

UPDATE:
I couldn't figure out the exact problem, however I made a fix that's good enough for me: Whenever the player's X value is less then half the screen's width, I just snap the view back to the center (up left corner) using sf::View::setCenter().
So I'm working on a recreating of Zelda II to help learn SFML good enough so I can make my own game based off of Zelda II. The issue is the screen scrolling, for some reason, if link walks away from the wall and initiated the camera to follow him, and then move back toward the wall, the camera won't go all the way back to the end of the wall, which occurs on the other wall at the end of the scene/room. This can be done multiple times to keep making the said camera block get further away from the wall. This happens on both sides of the scene, and I have reason to believe it has something to do with me trying to make the game frame independent, here's an included GIF of my issue to help understand:
My camera function:
void Game::camera() {
if (this->player.getVar('x') >= this->WIDTH / 2 and this->player.getVar('x') < this->sceneWidth - this->WIDTH / 2) {
this->view.move(int(this->player.getVar('v') * this->player.dt * this->player.dtM), 0);
}
}
player.getVar() is a temporary function I'm using to get the players x position and x velocity, using the argument 'x' returns the players x position, and 'v' returns the x velocity. WIDTH is equal to 256, and sceneWidth equals 767, which is the image I'm using for the background's width. dt and dtM are variables for the frame independence I mentioned earlier, this is the deceleration:
sf::Clock sclock;
float dt = 0;
float dtM = 60;
int frame = 0;
void updateTime() {
dt = sclock.restart().asSeconds();
frame += 1 * dt * dtM;
}
updateTime() is called every frame, so dt is updated every frame as well. frame is just a frame counter for Link's animations, and isn't relevant to the question. Everything that moves and is rendered on the screen is multiplied by dt and dtM respectively.
There's a clear mismatch between the movement of the player and the one of the camera... You don't show the code to move the player, but if I guess you don't cast to int the movement there, as you are doing on the view.move call. That wouldn't be a problem if you were setting the absolute position of the camera, but as you are constantly moving it, the little offset accumulates each frame, causing your problem.
One possible solution on is to skip the cast, which is unnecessary because sf::View::move accepts float as arguments.
void Game::camera() {
if (this->player.getVar('x') >= this->WIDTH / 2 and this->player.getVar('x') < this->sceneWidth - this->WIDTH / 2) {
this->view.move(this->player.getVar('v') * this->player.dt * this->player.dtM, 0);
}
}
Or even better, not to use view.move but to directly set the position of the camera each frame. Something like:
void Game::camera() {
if (this->player.getVar('x') >= this->WIDTH / 2 and this->player.getVar('x') < this->sceneWidth - this->WIDTH / 2) {
this->view.setCenter(this->player.getVar('x'), this->view.getCenter().y);
}
}

In SFML Why does my projectile slows as it gets closer to target

I am creating a small 2D top-down program that will have a projectile created when the left mouse is pressed. Then the projectile moves toward a goal. My issue is that the projectile slows when it moves closer to the goal. It should remain the same speed. I looked into normalize thinking that would help but have had a hard time finding much on SFML normalize. What I did find has not helped.
Here is my update for my projectile (agents):
void agent::update(const sf::CircleShape* goal, sf::Time delta) {
direction = goal->getPosition() - body.getPosition();
sf::Vector2f newPos = body.getPosition() + sf::Vector2f(direction.x * speed * delta.asSeconds(), direction.y * speed * delta.asSeconds());
body.setPosition(newPos);
}
ps. I have it in asSeconds instead of asMilliseconds or it goes weird and lags.

Ball passing through paddle from certain angles

I'm creating a pong clone for school with C++ and SFML 2.1 and I'm having a little problem when the ball hits the left paddle at sharp angles (It goes through).
The right paddle works fine at all angles, and as far as i can remember they're using the same code.
This is the code I'm using for collision:
for (auto& it : collisionPaddles)
{
if (this->ballShape.getGlobalBounds().intersects(it->getGlobalPaddleBounds()))
{
float deltaDistance = (this->y + this->radius) - (it->y + it->height / 2);
bool fromLeft = true;
if ((ballAngle < (3*myMath::MY_PI/2) && ballAngle > myMath::MY_PI/2))
{
fromLeft = false;
}
else
{
fromLeft = true;
}
ballAngle = static_cast<float>(deltaDistance * (myMath::MY_PI/180));
if (fromLeft)
{
ballAngle = static_cast<float>(myMath::MY_PI - ballAngle);
}
moveBall(2);
}
}
That's not the way a good pong should be implemented. When your model of physics uses some deltas, you get a lot of artefacts. The one of most prominent is objects passing through each other. In such simple cases deltas should be used for animation only.
Here's the way I would solve it. When the ball gets its initial speed and vector of movement, I would calculate the whole path until it hits the player's baseline.
Calculate an initial ray from the current position of the ball, directed the same way it moves.
Intersect that ray with segments that consistute the borders of your field.
Calculate the time that is needed to reach that intersection point.
Calculate the new ray from the intersection point towards the new movement vector.
Repeat steps 2-4 until you hit a player's base line. Sum all the times.
Now you have a relative time of the hit with baseline and the place it will happen. Now on every frame you should
Check if that collision time has been between the previous frame and the current one. If it was,
Calculate the expected position of paddle at that moment.
If the segment of paddle contains that intersection point, it was reflected. Calculate the new path as described before.
This way you'll get true game mechanics that are not limited by most of the aspects of game development, i.e. FPS, sudden lags etc.

How to adjust a game loop frame rate?

I'm at the moment trying to Programm my first Game in SFML (and my first overall) but i ran into the Problem that i get a stutter about once a second. During such a stutter the Frametime is 3 to 4 times higher than normal which is really noticeable as long i don't run really high FPS (300+).
No Problem (at least atm) as performance is not an Issue, but:
When doing that my movement Method really freaks out and moves way way slower that it's supposed to do.
my Movement method:
void Player::Update(float frametime){
mMovementSpeedTimefactor = frametime * 60 / 1000.0f;
setMovementVector(sf::Vector2f( mMovementVector.x * mMovementSpeedTimefactor, mMovementVector.y *mMovementSpeedTimefactor));
validateMovement();
//std::cout << mTestClock->restart().asMilliseconds() << std::endl;
moveObject();
this->updateAnimation();
}
frametime is the frametime in Milliseconds, and i Multiply by 60, as my movementspeed is set as a value for pixel/second and not per frame.
movementspeed is 5, so the character should move 5 px per second, whatever FPS( and therefore Frametime) i have.
But: that gives me really jumpy movement, as those "stutterframes" result in a jump, and on nto stuttering frames the palyer moves a lot slower than it should.
my mainloop is really simple, just
while(mMainWindow->isOpen()){
HandleEvents();
Update();
Render();
}
while using the inbuild framelimiter (tried writing my own, but i get the very same result, as long as i use sf:sleep to regulate FPS for not having the cpu core running at 100% load) to 300 FPS.
So yeah, i could just set my standard speed to 1 instead of 5, but
setframeratelimit is not very accurate, so i get some variation in movementspeed, that i really not like.
anyone has an idea, what i could best do? Maybe i'm not seeing the forest for all the trees ( i actually have no idea if you say that in english :P) but as this is my first game i have no experience to look back upon.
Similar question: Movement Without Framerate Limit C++ SFML.
What you really need is fixed time step.
Take a look at the SFML Game development book source code. Here's the interesting snippet from Application.cpp:
const sf::Time Game::TimePerFrame = sf::seconds(1.f/60.f);
[...]
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
while (mWindow.isOpen())
{
sf::Time elapsedTime = clock.restart();
timeSinceLastUpdate += elapsedTime;
while (timeSinceLastUpdate > TimePerFrame)
{
timeSinceLastUpdate -= TimePerFrame;
processEvents();
update(TimePerFrame);
}
updateStatistics(elapsedTime);
render();
}
EDIT: If this is not really what you want, see "Fix your timestep!" which Laurent Gomila himself linked in the SFML forum.
When frametime is really high or really low your calculations may not work correctly because of float precision issues. I suggest setting standard speed to, maybe, 500 and mMovementSpeedTimeFactor to frametime * 60 / 10.0f and check if the issue still happens.

How to programmatically move a window slowly, as if the user were doing it?

I am aware of the MoveWindow() and SetWindowPos() functions. I know how to use them correctly. However, what I am trying to accomplish is move a window slowly and smoothly as if a user is dragging it.
I have yet to get this to work correctly. What I tried was getting the current coordinates with GetWindowRect() and then using the setwindow and movewindow functions, incrementing Right by 10 pixels each call.
Any ideas?
Here is what I had beside all my definitions.
while(1)
{
GetWindowRect(notepad,&window);
Sleep(1000);
SetWindowPos(
notepad,
HWND_TOPMOST,
window.top - 10,
window.right,
400,
400,
TRUE
);
}
If you want smooth animation, you'll need to make it time-based, and allow Windows to process messages in between movements. Set a timer, and respond to WM_TIMER notifications by moving the window a distance based on the elapsed time since your animation started. For natural-looking movement, don't use a linear function for determining the distance - instead, try something like Robert Harvey's suggested function.
Pseudocode:
//
// animate as a function of time - could use something else, but time is nice.
lengthInMS = 10*1000; // ten second animation length
StartAnimation(desiredPos)
{
originalPos = GetWindowPos();
startTime = GetTickCount();
// omitted: hwnd, ID - you'll call SetTimer differently
// based on whether or not you have a window of your own
timerID = SetTimer(30, callback);
}
callback()
{
elapsed = GetTickCount()-startTime;
if ( elapsed >= lengthInMS )
{
// done - move to destination and stop animation timer.
MoveWindow(desiredPos);
KillTimer(timerID);
}
// convert elapsed time into a value between 0 and 1
pos = elapsed / lengthInMS;
// use Harvey's function to provide smooth movement between original
// and desired position
newPos.x = originalPos.x*(1-SmoothMoveELX(pos))
+ desiredPos.x*SmoothMoveELX(pos);
newPos.y = originalPos.y*(1-SmoothMoveELX(pos))
+ desiredPos.y*SmoothMoveELX(pos);
MoveWindow(newPos);
}
I found this code which should do what you want. It's in c#, but you should be able to adapt it:
increment a variable between 0 and 1 (lets call it "inc" and make it global) using small increments (.03?) and use the function below to give a smooth motion.
Math goes like this:
currentx=x1*(1-smoothmmoveELX(inc)) + x2*smoothmmoveELX(inc)
currenty=y1*(1-smoothmmoveELX(inc)) + y2*smoothmmoveELX(inc)
Code:
public double SmoothMoveELX(double x)
{
double PI = Atn(1) * 4;
return (Cos((1 - x) * PI) + 1) / 2;
}
http://www.vbforums.com/showthread.php?t=568889
A naturally-moving window would accelerate as it started moving, and decelerate as it stopped. The speed vs. time graph would look like a bell curve, or maybe the top of a triangle wave. The triangle wave would be easier to implement.
As you move the box, you need to steadily increase the number of pixels you are moving the box each time through the loop, until you reach the halfway point between point a and point b, at which you will steadily decrease the number of pixels you are moving the box by. There is no special math involved; it is just addition and subtraction.
If you are bored enough, you can do loopback VNC to drag the mouse yourself.
Now, as for why you would want to I don't know.