This site requires JavaScript, please enable it in your browser!
Greenfoot back
Moho
Moho wrote ...

2015/1/17

I dont want to press 2 buttons at a time

Moho Moho

2015/1/17

#
i dont want the game to register 2 buttons at a time so in other words i dont want the players to go in a diagonal line only left right and up and down.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Red here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Red extends Players
{
    /**
     * Act - do whatever the Red wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        move();
        //trail();
        //delay();
        //win();
    } 

    public void move()
    {
        if(Greenfoot.isKeyDown("up"))
        {
            setLocation(getX(), getY()-4);

        }   
        if (Greenfoot.isKeyDown("down"))
        {
            setLocation(getX(), getY()+4);
        }
        if (Greenfoot.isKeyDown("right"))
        {
            setLocation(getX()+4, getY());
        }
        if (Greenfoot.isKeyDown("left"))
        {
            setLocation(getX()-4, getY());
        }
    }
    public void trail()
    {
       
    }
    public void win()
    {
        
        
    }
}
danpost danpost

2015/1/17

#
I usually code 4-way movement like this:
public void move()
{
    int dx = 0;
    int dy = 0;
    if (Greenfoot.isKeyDown("left")) dx--;
    if (Greenfoot.isKeyDown("right")) dx++;
    if (Greenfoot.isKeyDown("up")) dy--;
    if (Greenfoot.isKeyDown("down")) dy++;
    if (dx*dy != 0 || dx+dy == 0) return;
    setLocation(getX()+4*dx, getY()+4*dy);
}
Line 9 first asks 'if neither is zero', then asks (or), 'if both are zero' (the second condition is only checked if at least one is already zero).
Moho Moho

2015/1/17

#
Well i just discovered thats not what i really wanted, although it temporarily resolved my problem. i found out that the game would be better if for example you press UP and it keeps going up until told otherwise IN ADDITION of not being able to go diagonal. Sorry if i annoyed you
danpost danpost

2015/1/17

#
For continuous:
private int xDirection, yDirection;

public void move()
{
    int dx = 0;
    int dy = 0;
    if (Greenfoot.isKeyDown("left")) dx--;
    if (Greenfoot.isKeyDown("right")) dx++;
    if (Greenfoot.isKeyDown("up")) dy--;
    if (Greenfoot.isKeyDown("down")) dy++;
    if (dx*dy == 0 && dx+dy != 0)
    {
        xDirection = dx;
        yDirection = dy;
    }
    setLocation(getX()+4*xDirection, getY()+4*yDirection);
}
You need to login to post a reply.