Well, I felt so genius when I found the obvious solution to my problem.
For all the time I have been coding, I never figured out how to get smooth movement, until I tried to make a small physics test (did not go well :P). But in doing that, I found my solution. It wasn’t even intentional!
You see, I wanted movement like this (yes, my own game; made immedietely after my ‘discovery’).
Originally, I was doing something amung the lines of this:
float accel = 0.3f;
float decel = -accel;
...
if(movingx)
this.xvel += accel;
else
this.xvel += decel;
if(movingy)
this.yvel += accel;
else
this.xvel += decel;
Very messy, nothing worked, and it was all just unnessacary.
So I was trying physics out, and came up with this!
// Variable for friction. NEVER let it go beneath 0.94. Otherwise you barely move.
float fric = 0.96f;
// Velocity vector. Self explainatory.
Vector2f velocity = Vector2f.get(0, 0);
// This is more of an 'applyForce()' method, but, ya know. YOLO (not. that is for dorks).
public void move(float x, float y) {
velocity.x += x;
velocity.y += y;
}
public void update(float delta) {
this.x += velocity.x*delta;
this.y += velocity.y*delta;
// This will dampen your movement. Clean and simple
velocity.x *= fric;
velocity.y *= fric;
}
Worked like a charm, was more efficient, and is easier to do! All this suffering, nights and nights trying to solve this… Simple solution… :P, :P, and :P.
Et Toi? Any major ‘DOH!’ moments in your coding?