How to create movement with acceleration/force? 2D platformer

So basically right now my character moves at a constant speed left and right and what I would like to
have is the character slowly speed up the longer the movement key (left or right) is pressed and then come to a
stop when its released.

Here is my move method right now.


public void move()
	{
		x += speed * dx;
		y += dy;
		
		if(y > 760 || y < 0)
		{
			dead = true;
			x = startX;
			y = startY;
		}

dx is the value that determines if he moves left or right, switches between 0, 1, -1
speed is a constant. currently set to 1.

If someone could update it and explain to me how works I would be super happy.

Thanks

well its called acceleration - another factor

you have the location x,y - the speed x,y and the the acceleration

the acceleration determines how fast the speed changes, and the speed determines how fast the object it moved/relocated

Yes I know how it works, I just have no idea how to implement it in code. which is what meant by my original question.

public void move()
   {
    speed = speed + dx;

      x += speed;
      y += dy;
      
      if(y > 760 || y < 0)
      {
         dead = true;
         x = startX;
         y = startY;
      }
}

You may want to cap the min and max of speed, and you may find that this acceleration is too fast, if so change speed, and x to a double and:

speed = dx * 0.001;
x = x + speed)

You can change 0.001 to your desired rate of acceleration. Also, for slowing down, if dx = 0 figure out if speed is negative or positive and head towards zero.

alright, now I tried to implement that but now I get an issue with my drawing of my image.

because x is now a double I get an error when I try to draw my image in my draw method.

g2d.drawImage(image,x,y,null);

So do I need to cast it back to an int? And if so wouldnt that just make my x be 1 and im back at having a constant speed of 1?

g2d.drawImage(image,(int)Math.round(x),y,null);

And gbeebe made a typo, should be:


speed += dx * 0.001;
x += speed;

even that did not work.

when I try to move, my sprite does not move at all, just stays stuck. but if I got back to a constant and not use doubles (which makes it so I cant have an acceleration) it works.

This cant be that hard, I have seen many games do this on here =\

Post all related code. This sounds like a casting error.

Alright, ill post the source in a zip if you like. or I can just jar it up with source included. so you can run and see what its like normally.

http://www.mediafire.com/?st3494f7osd9kue

The code is a bit sloppy and not very commented throughout most of it, I tend to do that until I get an end product im happy
with from which I go through, re-program it better and clean it up.

There are some glitches still needing to be worked out but anyways, the Player.java is the file you will find my move method in. Its being updated
from BlockmanMain.java

I put everything back to how I originally had it without the doubles so it will run on startup.

Just posting the character class here on JGO is enough >.<
Too lazy to download a jar, extract it, and look through all the source :smiley:

Alright, ill do that then my bad

A lot of the methods in the player class are not used, a lot were made and then abandoned I just have not cleaned them up yet.

PLAYER CLASS


public class Player extends Thread
{
	private Image image;
	private Thread animator; //animates the jump
	private boolean jump = false;
	private boolean jumping = false; //is in the middle of a jump
	private boolean done = false; //tells when jumping is done
	private boolean peak = false; //tells when at peak of jump
	private boolean falling = false; //if player is falling, or in the air still
	private boolean rising = false;
	private boolean movingRight = false;
	
	public boolean grounded = true;
	public boolean dead = false;
	
	private int width = 10;
	private int height = 10;
	
	private int x;
	private int y;
	private int startX;
	private int startY;
	
	private int dx;
	private int dy = 0;
	
	private int speed = 1;
	
	private int jumpHeight = 50;
	private int groundHeight;
	
	
	String url = "player.png";
	
	public Player()
	{
		ImageIcon ii = new ImageIcon(this.getClass().getResource("/images/player_2.png"));
		image = ii.getImage();
		groundHeight = y;
		
	}
	public void update()
	{
		move();
	}
	public void move()
	{
		x += speed * dx;
		y += dy;
		
		if(y > 760 || y < 0)
		{
			dead = true;
			x = startX;
			y = startY;
		}
		
	}
	public void jump()
	{
		
		if(!jump)
		{   
			grounded = false;
			jump = !jump;
			
			animator = new Thread(this);
			animator.start();
		}
	}
	public void draw(Graphics2D g2d)
	{
		g2d.drawImage(image,x,y,null);
	}
	public Image getImage()
	{
		return image;
	}
	public int getX()
	{
		return x;
	}
	public int getY()
	{
		return y;
	}
	public void setX(int x)
	{
		this.x = x;
	}
	public void setY(int y)
	{
		this.y = y;
	}
	public void setStartPoint(int x, int y)
	{
		this.startX = x;
		this.startY = y;
	}
	public void reset()
	{
		x = startX;
		y = startY;
		dx = 0;
		grounded = true;
	}
	public void restart()
	{
		x = startX;
		y = startY;
		dx = 0;
		dead = !dead;
		grounded = true;
	}
	public int getStartX()
	{
		return startX;
	}
	public int getStartY()
	{
		return startY;
	}
	public void setDx(int dx)
	{
		this.dx = dx;
	}
	public void shoveLeft(int amnt)
	{
		x -= amnt;
	}
	public void shoveRight(int amnt)
	{
		x += amnt;
	}
	public void shoveDown(int amnt)
	{
		y += amnt;
	}
	public void reverseDx()
	{
		this.dx *= -1;
	}
	public void stopJump()
	{
		done = true;
	}
	public void setDy(int dy)
	{
		this.dy = dy;
	}
	public int getDy()
	{
		return dy;
	}
	public void correctY(int y)
	{
		this.y = y - height;
	}
	public int getCenterX()
	{
		return (int) (width/2);
	}
	public int getCenterY()
	{
		return (int) (height/2);
	}
	public void setGroundHeight(int height)
	{
		this.groundHeight = height;
	}
	public boolean isRising()
	{
		return rising;
	}
	public boolean isFalling()
	{
		return falling;
	}
	public boolean isMovingRight()
	{
		return movingRight;
	}
	public void movingRight(boolean right)
	{
		this.movingRight = right;
	}
	public void setPeak(boolean peaked)
	{
		this.peak = peaked;
	}
	public boolean isJumping()
	{
		return jumping;
	}
	public Rectangle getBounds()
	{
		return new Rectangle(x,y,width,height);
	}
	
	//Thread for jumping
	@Override
	public void run()
	{
		long beforeTime, timeDiff, sleep;
		
		beforeTime = System.currentTimeMillis();
		
		while(done == false)
		{
			cycle();
			timeDiff = System.currentTimeMillis() - beforeTime;
			sleep = 8 - timeDiff;
			if(sleep < 0)
				sleep = 2;
			try
			{
				Thread.sleep(sleep);
			}
			catch(Exception e){e.printStackTrace();}
			beforeTime = System.currentTimeMillis();
		}
		done = false;
		jump = false;
		peak = false;
	}
	public void cycle()
	{
		if(peak == false)
		{
			rising = true;
			y-=3;
		}
		if(y <= (groundHeight-jumpHeight))
		{
			peak = true;
			rising = false;
		}
		if(peak == true && (y+height) <= groundHeight)
		{
			rising = false;
			setDy(1);
		}
			if((y+height) == groundHeight && !falling)
				done = true;
			else if((y+height) == groundHeight && falling)
			{
				groundHeight = 760;
				done = true;
			}	
	}
}

BLOCKMAN MAIN CLASS


public class BlockmanMain extends Game
{
	private static GameLoop gameLoop = new GameLoop();
	private Map map;
	private Player player = new Player();
	private CompletionPoint compPoint;
	int x = 0;
	public int level = 1;
	private final int MAX_LEVEL = 3;
	public static void main(String[] args)
	{
		GameStart.start(new BlockmanMain(), gameLoop);
	}
	
	public BlockmanMain()
	{
		title = "Epic Stuble Man!";
		background = Color.black;
		width = 1300;
		height = 760;
		delay = 5; //milliseconds between updates
	}
	@Override
	public void init()
	{
		/*
		 * Initialize variables here
		 * 
		 */
		
		over = false;
		map = new Map();
		LoadMap();
		//map.start();
		player.reset();
		
	}

	public void LoadMap()
	{
		map.clear();
		int mapH = 72; //map height
		int mapW = 128; //map width
		String url = "maps/Level_"+level+".txt";
		InputStream in = BlockmanMain.class.getResourceAsStream(url);
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		
		int x = 0;
		int y = 0;
		try
		{
			
			for (int i = 0; i < mapH; i++)
			{
				char line[] = reader.readLine().toCharArray();
				for (int j = 0; j < mapW; j++)
				{
					if(line[j] == '#')
					{
						map.addPath(x,y);
					}
					if(line[j] == '_')
					{
						map.addFallingPath(x,y);
					}
					else if(line[j] == '^')
					{
						map.addSpike(x,y,true);
					}
					else if(line[j] == '.')
					{
						map.addSpike(x, y,false);
					}
					else if(line[j] == '*')
					{
						map.addEnemy(x, y,true);
					}
					else if(line[j] == '$')
					{
						player.setStartPoint(x, y);
					}
					else if(line[j] == '@')
					{
						compPoint = new CompletionPoint(x, y);
					}
					x += 10;
				}
				x = 0;
				y+=10;
			}reader.close();
			map.loadingLevel = false;
			map.startThread();
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
	}

	@Override
	public void update()
	{
		/*
		 * Call update methods here
		 * 
		 */
		if(player.dead) //Resets map is player dies
		{
			map.loadingLevel = true; //stop the map thread
			map.clear(); //clear the map
			LoadMap(); //load the map
			player.restart(); //restart
		}
		
		if(!map.loadingLevel)
		{
			map.update(player);
			player.update();
		}
		
		if(player.getBounds().intersects(compPoint.getBounds()))
		{
			level++;
			if(level <= MAX_LEVEL)
			{
				
				map.loadingLevel = true;
				map.clear();
				LoadMap();
				player.reset();
			}
			else
			{
				map.clear();
			}
		}
	}

	@Override
	public void draw(Graphics2D g2d)
	{
		/*
		 * Call draw methods here
		 * 
		 */
		if(level <= MAX_LEVEL)
		{
			g2d.setFont(new Font("Chiller", Font.BOLD, 28));
			g2d.setColor(Color.white);
			g2d.drawString("Level: "+level, 1180, 25);
			if(compPoint != null)
				g2d.drawImage(compPoint.getImage(), compPoint.getX(), compPoint.getY(),null);
			
			if(!map.loadingLevel)
			{
				map.draw(g2d);
				if(player != null)
					player.draw(g2d);
			}
		}
		else
		{
			g2d.setFont(new Font("Chiller", Font.BOLD, 48));
			g2d.setColor(Color.green);
			g2d.drawString("WINNER! YOU HAVE BEATEN THE GAME!", width/2 - 400, height/2 - 48);
		}
	}
	public void keyPressed(KeyEvent e)
	{
		
		switch(e.getKeyCode())
		{
			case KeyEvent.VK_W:
				break;
			case KeyEvent.VK_A:
				player.setDx(-1);
				player.movingRight(false);
				break;
			case KeyEvent.VK_S:
				break;
			case KeyEvent.VK_D:
				player.setDx(1);
				player.movingRight(true);
				break;
			case KeyEvent.VK_SPACE:
				if(player.grounded)
				{
					player.jump();
				}
				break;
		}
	}
	public void keyReleased(KeyEvent e)
	{
		/*
		 * Set Dx's to 0 when released
		 * 
		 */
		switch(e.getKeyCode())
		{
			case KeyEvent.VK_W:
				break;
			case KeyEvent.VK_A:
				player.setDx(0);
				break;
			case KeyEvent.VK_S:
				break;
			case KeyEvent.VK_D:
				player.setDx(0);
				break;
		}
	}
}


Everything is an “int” and you’re only adding speed * dx…

yes I know that, I said I put everything back to normal.

It was not working having them as doubles and casting to an int with math.round

This is the same class with how you told me to do it. which, makes it so I cant move at all.


public class Player extends Thread
{
	private Image image;
	private Thread animator; //animates the jump
	private boolean jump = false;
	private boolean jumping = false; //is in the middle of a jump
	private boolean done = false; //tells when jumping is done
	private boolean peak = false; //tells when at peak of jump
	private boolean falling = false; //if player is falling, or in the air still
	private boolean rising = false;
	private boolean movingRight = false;
	
	public boolean grounded = true;
	public boolean dead = false;
	
	private int width = 10;
	private int height = 10;
	
	private double x;
	private int y;
	private int startX;
	private int startY;
	
	private int dx;
	private int dy = 0;
	
	private double speed = 1;
	
	private int jumpHeight = 50;
	private int groundHeight;
	private double accel = .001;
	
	String url = "player.png";
	
	public Player()
	{
		ImageIcon ii = new ImageIcon(this.getClass().getResource("/images/player_2.png"));
		image = ii.getImage();
		groundHeight = y;
		
	}
	public void update()
	{
		move();
	}
	public void move()
	{
		speed = dx * accel;
		
		x+=speed;
		//x += speed * dx;
		y += dy;
		
		if(y > 760 || y < 0)
		{
			dead = true;
			x = startX;
			y = startY;
		}
		
	}
	public void jump()
	{
		
		if(!jump)
		{   
			grounded = false;
			jump = !jump;
			
			animator = new Thread(this);
			animator.start();
		}
	}
	public void draw(Graphics2D g2d)
	{
		g2d.drawImage(image,(int)Math.round(x),y,null);
	}
	public Image getImage()
	{
		return image;
	}
	public double getX()
	{
		return x;
	}
	public int getY()
	{
		return y;
	}
	public void setX(int x)
	{
		this.x = x;
	}
	public void setY(int y)
	{
		this.y = y;
	}
	public void setStartPoint(int x, int y)
	{
		this.startX = x;
		this.startY = y;
	}
	public void reset()
	{
		x = startX;
		y = startY;
		dx = 0;
		grounded = true;
	}
	public void restart()
	{
		x = startX;
		y = startY;
		dx = 0;
		dead = !dead;
		grounded = true;
	}
	public int getStartX()
	{
		return startX;
	}
	public int getStartY()
	{
		return startY;
	}
	public void setDx(int dx)
	{
		this.dx = dx;
	}
	public void shoveLeft(int amnt)
	{
		x -= amnt;
	}
	public void shoveRight(int amnt)
	{
		x += amnt;
	}
	public void shoveDown(int amnt)
	{
		y += amnt;
	}
	public void reverseDx()
	{
		this.dx *= -1;
	}
	public void stopJump()
	{
		done = true;
	}
	public void setDy(int dy)
	{
		this.dy = dy;
	}
	public int getDy()
	{
		return dy;
	}
	public void correctY(int y)
	{
		this.y = y - height;
	}
	public int getCenterX()
	{
		return (int) (width/2);
	}
	public int getCenterY()
	{
		return (int) (height/2);
	}
	public void setGroundHeight(int height)
	{
		this.groundHeight = height;
	}
	public boolean isRising()
	{
		return rising;
	}
	public boolean isFalling()
	{
		return falling;
	}
	public boolean isMovingRight()
	{
		return movingRight;
	}
	public void movingRight(boolean right)
	{
		this.movingRight = right;
	}
	public void setPeak(boolean peaked)
	{
		this.peak = peaked;
	}
	public boolean isJumping()
	{
		return jumping;
	}
	public Rectangle getBounds()
	{
		return new Rectangle((int)x,y,width,height);
	}
	
	//Thread for jumping
	@Override
	public void run()
	{
		long beforeTime, timeDiff, sleep;
		
		beforeTime = System.currentTimeMillis();
		
		while(done == false)
		{
			cycle();
			timeDiff = System.currentTimeMillis() - beforeTime;
			sleep = 8 - timeDiff;
			if(sleep < 0)
				sleep = 2;
			try
			{
				Thread.sleep(sleep);
			}
			catch(Exception e){e.printStackTrace();}
			beforeTime = System.currentTimeMillis();
		}
		done = false;
		jump = false;
		peak = false;
	}
	public void cycle()
	{
		if(peak == false)
		{
			rising = true;
			y-=3;
		}
		if(y <= (groundHeight-jumpHeight))
		{
			peak = true;
			rising = false;
		}
		if(peak == true && (y+height) <= groundHeight)
		{
			rising = false;
			setDy(1);
		}
			if((y+height) == groundHeight && !falling)
				done = true;
			else if((y+height) == groundHeight && falling)
			{
				groundHeight = 760;
				done = true;
			}	
	}
}

As I pointed out earlier, gbeebe was wrong, it’s speed += dx * accel;
0.001 is a really small number, make it 0.1 for now.

ah alright, that seems to work now.

but now it even when dx is 0 it moves right. so thats something ill have to figure out now.

nvm, i was having my x += speed which was causing it.

Ah glad you solved it :slight_smile:

Yea thanks for the help both of you.