Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 14 of 14

Thread: Movement Error

  1. #1
    Junior Member
    Join Date
    Nov 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Movement Error

    I know there may be a forum particularly for this below, but this is sort of urgent for me. I am creating a game in Eclipse and have came across a glitch which I cannot figure out how to solve at all, I am a beginner here so I've probably missed something that a more experienced user can find. I have implemented movement into my game, however it can only move sideways regardless of pressing W, S or turning around. I am positive that I've filled it out properly, I've looked on the tutorial for movement and I cannot find any error I've made with this. Here's the code:

    'Game'

    package base.dragonlord;
     
    import java.awt.event.KeyEvent;
     
    public class Game {
    	public int time;
    	public Controller controls;
     
    	public Game() {
    		controls = new Controller();
     
    	}
     
    	public void tick(boolean[] key) {
    		time++;
    		boolean forward = key[KeyEvent.VK_W];
    		boolean back = key[KeyEvent.VK_S];
    		boolean left = key[KeyEvent.VK_A];
    		boolean right = key[KeyEvent.VK_D];
     
    		controls.tick(forward, back, left, right);
    	}
     
     
    }

    'Input Handler'

    package base.dragonlord;
     
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
     
    public class InputHandler implements KeyListener, FocusListener, MouseListener, MouseMotionListener {
     
    	public boolean[] key = new boolean[68836];
    	public static int MouseX;
    	public static int MouseY;
     
    	@Override
    	public void keyPressed(KeyEvent e) {
    		int keyCode = e.getKeyCode();
    		if (keyCode > 0 && keyCode < key.length) {
    			key[keyCode] = true;
    		}
    	}
     
    	@Override
    	public void keyReleased(KeyEvent e) {
    		int keyCode = e.getKeyCode();
    		if (keyCode > 0 && keyCode < key.length) {
    			key[keyCode] = false;
    		}
    	}
     
    	@Override
    	public void keyTyped(KeyEvent e) {
    	}
     
    	@Override
    	public void focusGained(FocusEvent e) {
    	}
     
    	@Override
    	public void focusLost(FocusEvent e) {
    		for (int i = 0; i < key.length; i++) {
    			key[i] = false;
    		}
    	}
     
    	@Override
    	public void mouseClicked(MouseEvent e) {
    	}
     
    	@Override
    	public void mouseEntered(MouseEvent e) {
    	}
     
    	@Override
    	public void mouseExited(MouseEvent e) {
    	}
     
    	@Override
    	public void mousePressed(MouseEvent e) {
    	}
     
    	@Override
    	public void mouseReleased(MouseEvent e) {
    	}
     
    	@Override
    	public void mouseDragged(MouseEvent e) {
    	}
     
    	@Override
    	public void mouseMoved(MouseEvent e) {
    		MouseX = e.getX();
    		MouseY = e.getY();
    	}
     
    }

    'Controller'

    package base.dragonlord;
     
    public class Controller {
     
    	public double x, z, rotation, xa, za, rotationa;
    	public static boolean turnLeft = false;
    	public static boolean turnRight = false;
     
    	public void tick(boolean forward, boolean back, boolean left, boolean right) {
    		double rotationSpeed = 0.025;
    		double walkSpeed = 1;
    		double xMove = 0;
    		double zMove = 0;
     
    		if (forward) {
    			zMove++;
    		}
     
    		if (back) {
    			zMove--;
    		}
     
    		if (left) {
    			xMove--;
    		}
     
    		if (right) {
    			xMove++;
     
    		}
     
    		if (turnLeft) {
    			rotationa -= rotationSpeed;
     
    		}
     
    		if (turnRight) {
    			rotationa += rotationSpeed;
     
    		}
     
    		xa += (xMove * Math.cos (rotation) + zMove * Math.sin (rotation)) * walkSpeed;
    		za += (zMove * Math.cos (rotation) - xMove * Math.sin (rotation)) * walkSpeed;		
     
    		x += xa;
    		x += za;
    		xa *= 0.1;
    		za *= 0.1;
    		rotation += rotationa;
    		rotationa *= 0.5;
     
    	}
     
    }

    Please help me out here !


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Movement Error

    How are these parts wired together? Where is the class with the main() method that gets the ball rolling?

  3. #3
    Junior Member
    Join Date
    Nov 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Movement Error

    I wasn't sure if I had to post that, I am sure it's an error contained in the other pieces of code I pasted - I just can't find it. Here's the class that contains the main() method:

    package base.dragonlord;
     
    import java.awt.Canvas;
    import java.awt.Cursor;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.Toolkit;
    import java.awt.image.BufferStrategy;
    import java.awt.image.BufferedImage;
    import java.awt.image.DataBufferInt;
     
    import javax.swing.JFrame;
     
    public class Display extends Canvas implements Runnable {
     
    	public static final int WIDTH = 800;
    	public static final int HEIGHT = 600;
    	public static final String TITLE = "Dragonlord - Pre-Alpha - Version 0.02";
     
    	private Thread thread;
    	private Screen screen;
    	private Game game;
    	private BufferedImage img;
    	private boolean running = false;
    	private int[] pixels;
    	private InputHandler input;
    	private int oldX = 0;
    	private int newX = 0;
    	private int oldY = 0;
     
    	public Display() {
    		Dimension size = new Dimension(WIDTH, HEIGHT);
    		setPreferredSize(size);
    		setMinimumSize(size);
    		setMaximumSize(size);
    		screen = new Screen(WIDTH, HEIGHT);
    		game = new Game();
    		img = new BufferedImage (WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    		pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
     
    		input = new InputHandler();
    		addKeyListener(input);
    		addFocusListener(input);
    		addMouseListener(input);
    		addMouseMotionListener(input);
     
    	}
     
    	private void start() {
    		if (running)
    			return;
    		running = true;
    		thread = new Thread(this);
    		thread.start();	
     
    		System.out.print("Working!");
     
    	}
     
    	private void stop() {
    		if (running)
    			return;
    		running = false;
    		try {
    		thread.join();
    		} catch (Exception e) {
    			e.printStackTrace();
    			System.exit(0);
    		}
    	}
     
    	public void run() {
    		int frames = 0;
    		double unprocessedSeconds = 0;
    		long previousTime = System.nanoTime();
    		double secondsPerTick = 1 / 60.0;
    		int tickCount = 0;
    		boolean ticked = false;
     
    		while (running) {
    			long currentTime = System.nanoTime();
    			long passedTime = currentTime - previousTime;
    			previousTime = currentTime;
    			unprocessedSeconds += passedTime / 1000000000.0;
     
    			while (unprocessedSeconds > secondsPerTick) {
    				tick();
    				unprocessedSeconds -= secondsPerTick;
    				ticked = true;
    				tickCount++;
    				if (tickCount % 60 == 0) {
    					System.out.println(frames + "FPS");
    					previousTime += 1000;
    					frames = 0;
    				}
    			}
    			if (ticked) {
    				render();
    				frames++;
    			}
    			render();
    			frames++;
     
    			newX = InputHandler.MouseX;
    			if (newX > oldX) {
    				System.out.println ("Right");
    				Controller.turnRight = true;
    			}
     
    			newX = InputHandler.MouseX;
    			if (newX < oldX) {
    				System.out.println ("Left");
    				Controller.turnLeft = true;
    			}
    			if (newX == oldX) {
    				Controller.turnLeft = false;
    				Controller.turnRight = false;
    			}
    			oldX = newX;
    		}
    	}
     
    	private void tick() {
    		game.tick(input.key);
     
    	}
     
    	private void render() {
    		BufferStrategy bs = this.getBufferStrategy();
    		if (bs == null) {
    			createBufferStrategy(3);
    			return;
    		}
     
    		screen.render(game);
     
    		for (int i = 0; i <WIDTH * HEIGHT; i++) {
    			pixels[i] = screen.pixels[i];
    		}
     
    		Graphics g = bs.getDrawGraphics();
    		g.drawImage(img, 0, 0, WIDTH + 10, HEIGHT + 10, null);
    		g.dispose();
    		bs.show();
    	}
     
    	public static void main(String[] args) {
    		BufferedImage cursor = new BufferedImage (16, 16, BufferedImage.TYPE_INT_ARGB);
    		Cursor blank = Toolkit.getDefaultToolkit().createCustomCursor(cursor, new Point(0,0), "blank");
    		Display game = new Display();
    		JFrame frame = new JFrame();
    		frame.add(game);
    		frame.pack();
    		frame.getContentPane().setCursor(blank);
    		frame.setTitle(TITLE);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		//frame.setSize(WIDTH, HEIGHT);
    		frame.setLocationRelativeTo(null);
    		frame.setResizable(false);
    		frame.setVisible(true);
     
    		System.out.println("Running...");
     
    		game.start();
    	}
     
    }

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Movement Error

    Let's trade places . . .

    If someone handed you this mass of code and said "Things don't move when they're supposed to. Help me fix it." What would you say? At a minimum, you'd probably say, "Show me."

    Seriously. There isn't one comment, not one clue what this program does, how it's supposed to do what it does (except that it doesn't do it), how the classes are related, how they work together, nothing. AND, it's not even runnable to give us the "show me" experience and a chance at figuring those things out, because we don't have all of the code. We're not psychic.

    We like to help others, solve puzzles, give new programmers insight from our many years of combined experience, but we're not miracle workers. Give us the info we need to help you.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Movement Error

    The approach I take to find out why code does what it does is to debug it.
    I use the println() statement to print out messages in every method that is called and to print the values of variables as there values are changed. If you understand what the code is supposed to do when it executes,
    the print out will show you what the code is doing when it executes. That will show you where the code is not doing what you want it to do.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Nov 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Movement Error

    Quote Originally Posted by GregBrannon View Post
    Let's trade places . . .

    If someone handed you this mass of code and said "Things don't move when they're supposed to. Help me fix it." What would you say? At a minimum, you'd probably say, "Show me."

    Seriously. There isn't one comment, not one clue what this program does, how it's supposed to do what it does (except that it doesn't do it), how the classes are related, how they work together, nothing. AND, it's not even runnable to give us the "show me" experience and a chance at figuring those things out, because we don't have all of the code. We're not psychic.

    We like to help others, solve puzzles, give new programmers insight from our many years of combined experience, but we're not miracle workers. Give us the info we need to help you.
    I figured pasting the code for the parts that execute movement were enough. Should I give you the whole thing?

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Movement Error

    parts that execute movement were enough
    Maybe with a simple program. More complicated programs need to be executed to see what they are doing.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Nov 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Movement Error

    Ok, here it is.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Movement Error

    Please post the code on the forum, not links.

    You could also start debugging the code as I suggested in post#5.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Nov 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Movement Error

    Which code do you want me to post? I posted the full code for the classes that involve movement, what more?

    The problem with your suggestion is that when I attempt to move forward it will say it's moving forward when it's not, it will be moving sideways only.

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Movement Error

    The problem with your suggestion is that when I attempt to move forward it will say it's moving forward when it's not, it will be moving sideways only.
    Can you explain how my suggestion is a problem?
    A way you find problems in your code is to debug it. I use println()s. Try adding some to see why "it will be moving sideways only."

    To execute the code, it needs to compile. Right now its missing the Screen class.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Junior Member
    Join Date
    Nov 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Movement Error

    I've given you the whole program as one of you asked and that still wasn't enough for any of you, println()'s isn't efficient enough for me.

    Is there a way to delete this thread?

  13. #13
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Movement Error

    Thought you'd given up. I haven't figured out why, but if you add a print statement to the Game.tick() method, something like:
    public void tick(boolean[] key)
    {
        time++;
        boolean forward = key[KeyEvent.VK_W];
        boolean back = key[KeyEvent.VK_S];
        boolean left = key[KeyEvent.VK_A];
        boolean right = key[KeyEvent.VK_D];
     
        System.out.println( "forward = " + forward + "\nback = " + back );
        System.out.println( "left = " + left + "\nright = " + right );
     
        controls.tick(forward, back, left, right);
    }
    the forward and back movement will occur with key presses. Again, not sure why, but the miles of uncommented code is unpleasant to unravel.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Movement Error

    println()'s isn't efficient enough for me.
    Are you using an IDE with interactive debug? That could be "more efficient" for you.
    It's a personal preference which way to debug a program. I find the use of println()s to be better in some cases where there is lots of code to be executed and the whole of the debug output can be generated quickly instead of having to step from statement to statement observing the contents of the variables as the code executes.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. GUI mouse movement
    By crise1967 in forum AWT / Java Swing
    Replies: 3
    Last Post: April 25th, 2012, 08:40 AM
  2. WASD Movement! Need Help!
    By Alex555 in forum Java Theory & Questions
    Replies: 12
    Last Post: April 19th, 2012, 12:59 PM
  3. How to control gain between mouse movement and cursor movement ?
    By DrPete in forum Java Theory & Questions
    Replies: 3
    Last Post: March 12th, 2012, 07:27 AM
  4. 3D camera movement
    By macko in forum Java Theory & Questions
    Replies: 2
    Last Post: May 17th, 2011, 07:53 AM
  5. movement
    By mlan in forum Java Theory & Questions
    Replies: 4
    Last Post: February 15th, 2010, 10:57 PM