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

2015/1/18

Random Moving Enemy on X axis?

JohnFox JohnFox

2015/1/18

#
Hi i'm attempting to put together my first game after following a tutorial from my course. Th piece of code i have makes my enemy go back and forth along the Y axis: private void autoMove() { if (forward == true) move(3); else move(-3); //ENDIF if(getX()>=getWorld().getWidth()-1) forward=false; if(getX()<=1) forward=true; } I would like him to be moving along the X axis only on the right hand side of the screen and if possible have the movement randomly going up and down so as not to be too predictable. Please Help!!!
-nic- -nic-

2015/1/18

#
At the moment the

if (forward == true)
        move(3);
     else
        move(-3);
    
 
Code is moving the enemy left to right which is the X-axis I'm guessing you want the enemy to move up and down when at the right hand side of the screen To do this:
if(getX()>getWorld().getWidth()/2)//test if enemy is on the right side of the screen 
        {
            int upDown = Greenfoot.getRandomNumber(10)-5;//make a random number to go up or down by between -5 and 5
            setLocation(getX(),getY()+upDown);//set location with the current x position and our current y position but adjusted using the upDown variable
        }

JohnFox JohnFox

2015/1/18

#
Hi nic, thanks for your reply! That has worked and my my enemy is now going up and down on the right hand side. The movements are a quite fast and a bit jerky, is there any way of slowing it down? Thanks again, John
Super_Hippo Super_Hippo

2015/1/18

#
Well, I think this should work. But better test and adjust it.
private int timer = 0, ydirection = -1, xdirection = 1;

public void act()
{
    if (getX() < getWorld().getWidth()/2) xdirection=1;
    if (getX() > getWorld().getWidth()-10) xdirection=-1;
    
    timer++;
    if (timer > 50 && Greenfoot.getRandomNumber(20)==0 || direction==-1 && getY() < 100 || direction==1 && getY()>getWorld().getHeight()-10)
    {
        timer=0;
        direction *= -1;
    }
    setLocation(getX()+xdirection,getY()+ydirection);
}
smcgee smcgee

2015/10/29

#
I could not get the above code to work - but with a few simple changes I was able to get a car to randomly move on the X access randomly - thank you so much Super_Hipp! Here is my update to your code: public void act() { if (getX() < getWorld().getWidth()/2) xdirection=1; if (getX() > getWorld().getWidth()-10) xdirection=-1; timer++; if (timer > 50 && Greenfoot.getRandomNumber(20)==0 || ydirection==-1 && getY() < 100 || xdirection==1 && getY()>getWorld().getHeight()-10) { timer=0; ydirection *= -1; } setLocation(getX()+xdirection,getY()+ydirection); }
You need to login to post a reply.