0

Currently I'm working on a simple 2d platformer, and I decided to work on physics before working on the general concept of the game. I actually haven't learned physics in school or anything, so I'm just using google/youtube tutorials as my main resources. I've currently gotten jumping working pretty nicely, but moving side to side isn't what I would like it to be. I want it to use acceleration/deceleration vs. just incrementing/decrementing the x position by a constant speed. Now I've tried using this website for x motion but that seems to be what I'm using for jumping. Here is my current player class:

import game.Game;
import game.input.PlayerController;

public class Player {

    private float dt = 0.18F, gravity = 9.81F;
    public float x, y, dx, dy;
    private PlayerController controller;
    private boolean jumping, onGround;

    public float speed = 7.5F;
    public float jh = 60F;
    public float vy = 120F;

    public Player() {
        controller = new PlayerController();
    }

    public void update() {
        controller.update(this);

        dy += gravity * dt * (jumping ? -1F : 1F);

        if(!jumping && !onGround && dy > vy) dy = vy;

        y += dy * dt + 0.5F * gravity * dt * dt;
        x += dx;

        if (y > Game.height - 32) {
            dy = 0;
            y = Game.height - 32;
            onGround = true;
        } else
            onGround = false;

        if(dy < jh) { jumping = false;}

        dx = 0;
    }

    public void render(Graphics g) {
        g.setColor(Color.red);
        g.fillRect(x, y, 32, 32);
    }

    public void moveLeft() {
        dx -= speed;
    }

    public void moveRight() {
        dx += speed;
    }

    public void jump() {
        if (onGround) {
            jumping = true;
            dy -=jh;
        }
    }
}

In the PlayerController class I'm just calling player.moveLeft() and player.moveRight() when the left and right keys are pressed.

If anybody has a good idea on how to make smoother movement, that would be very helpful. Thanks!

loafy
  • 105
  • 1
  • 11
  • You're problem will be that the loop isn't going to be running at a consistent speed. The way this is usually solved is by using interpolation or delta time. This post might help you out: http://www.java-gaming.org/index.php?topic=24220.0 – TechnoCF Apr 02 '16 at 23:39
  • @TechnoCF I'm updating/rendering the game 60 times per second, pretty sure this isn't the issue. – loafy Apr 02 '16 at 23:51
  • 1
    The computer will not be able to produce a perfect 60 updates per second. That is where delta time comes in, I ran in to the same issue when I started making games. The issue was that I wasn't taking into account the imperfections in the loop times and making up for those with delta time. – TechnoCF Apr 02 '16 at 23:52
  • @TechnoCF, ok thanks, didn't realize that. I'll look into it a bit later. – loafy Apr 03 '16 at 00:01

0 Answers0