Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Test - GameState.java

By: huneater on Apr 11th, 2013  |  syntax: Java  |  size: 2.01 KB  |  views: 55  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. package main;
  2.  
  3. import org.newdawn.slick.*;
  4. import org.newdawn.slick.state.BasicGameState;
  5. import org.newdawn.slick.state.StateBasedGame;
  6.  
  7. /**
  8.  * User: Zsolt
  9.  * Date: 2013.04.11.
  10.  * Time: 19:14
  11.  */
  12.  
  13. public class GameState extends BasicGameState {
  14.     float x = 100, y = 100; // player's location (starts from 100 by 100)
  15.     float targetX, targetY; // The targets for the player
  16.     float mouseX, mouseY;   // The mouse locations
  17.     Image player;           // The IMG file (player)
  18.  
  19.     @Override
  20.     public int getID() {
  21.         return 0; // This is used to jump between states ( stateBasedGame.enterState(GameState.getID()); )
  22.     }
  23.  
  24.     @Override
  25.     public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
  26.         player = new Image("res/bg.png"); // Init the image
  27.     }
  28.  
  29.     @Override
  30.     public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
  31.         player.draw(x - 50, y - 50, 100, 100); // Draw a 100 by 100 sized player
  32.     }
  33.  
  34.     @Override
  35.     public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
  36.         Input input = gc.getInput(); // Store all inputs in this input object
  37.         mouseX = input.getMouseX();  // Get mouseX from the input
  38.         mouseY = input.getMouseY();  // Get mouseY from the input
  39.  
  40.         // 0 = left; 1 = right mouse button
  41.         if (input.isMouseButtonDown(0)) {
  42.             targetX = mouseX; // Set the target x to the mouseX
  43.             targetY = mouseY; // Set the target Y to the mouseY
  44.         }
  45.        
  46.         // Calculate the disrance between the current and the target locations
  47.         float length = (float) Math.sqrt((targetX - x) * (targetX - x) + (targetY - y) * (targetY - y));
  48.         float velocityX = (targetX - x) / length * delta * 1f;
  49.         float velocityY = (targetY - y) / length * delta * 1f;
  50.  
  51.         x += velocityX; // Add distance_x to the current location
  52.         y += velocityY; // Add distance_y to the current location
  53.     }
  54. }