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

2018/4/9

How do I create a randomly moving enemy along the X axis that moves side to side.

an123 an123

2018/4/9

#
I am trying to create a randomly moving enemy with a constant speed, but random direction and a limit to how far it can move along the y axis. It's very choppy and not smooth at all. here is the code below, please help!! int timer = 0; public void act() { timer ++; if (timer == 20) { move(); timer = 0; } } public void move() { if (RLevelOne.class.isInstance(getWorld())) { if(atLeftEdge()) { setLocation(getX()+10,getY()); } if(atRightEdge()) { setLocation(getX()-10,getY()); } if(atUpEdge()) { setLocation(getX(),getY()+10); } if(atDownEdge()) { setLocation(getX()+10,getY()-10); } setLocation(getX() + Greenfoot.getRandomNumber(10),getY() + Greenfoot.getRandomNumber(10)); } } private boolean atLeftEdge() { return (getX()>=getWorld().getWidth()-5); } private boolean atRightEdge() { return (getX()<= 5); } private boolean atUpEdge() { return (getY()<=5); } private boolean atDownEdge() { return (getY()>=getWorld().getHeight()/2); }
danpost danpost

2018/4/9

#
Your timer is restricting movement to about 3 shifts in position per second; also, your random movement is restricted toward the lower right corner of the world. I wonder if you really need the timer and for smoother movement, I do not see how using random distances is going to help with the movement -- especially since it is direction, not speed, you want randomized. I would scratch all this code and start afresh. For more help, you will have to give more details as to exactly how you want your enemies to behave -- in all situations. Use lots of adjectives for clarity.
You need to login to post a reply.