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

2014/5/18

How to make a car move either left or right when it is created?

Tommy99 Tommy99

2014/5/18

#
Hello. I am almost finished with my project, but I have one criteria that I just cannot seem to get. Here it is: The cars move either left or right. This information is given to the car when it is created. Hint: The constructor needs a parameter. Cars always face the direction they’re facing. Here is the code for the Car class: import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class Car extends Actor { GreenfootImage img = new GreenfootImage("car01.png"); GreenfootImage img2 = new GreenfootImage("car02.png"); GreenfootImage img3 = new GreenfootImage("car03.png"); private int c = Greenfoot.getRandomNumber(3); private boolean direction; public Car() { if(c==0){ setImage(img); } if(c==1){ setImage(img2); } if(c==2){ setImage(img3); } setRotation(180); } public Car(direction right) { if(c==0){ setImage(img); } if(c==1){ setImage(img2); } if(c==2){ setImage(img3); } setRotation(0); } public void act() { touchingGreep(); removeThis(); moveForward(); } public void touchingGreep() { int x = getWorld().getWidth()/2; int y = getWorld().getHeight()-50; Actor greep = getOneIntersectingObject(Greep.class); if(greep!=null){ getWorld().removeObject(greep); getWorld().addObject(new GameOverActor(), x, y); Greenfoot.stop(); } } public void removeThis() { if(getX()<3 || getX()>getWorld().getWidth()-3){ removeObject(this); } } public void moveForward() { move(5); } }
danpost danpost

2014/5/18

#
One major problem is that the constructor declaration on line 27 (or about there) has a parameter of unknown type. 'direction' is not a primitive type and I doubt you (nor should you) have a Object class (extending World, Actor, or otherwise) with that name. Please refer to this page of the Java tutorials for more information.
danpost danpost

2014/5/18

#
You should also move line 44 to after line 45 (call 'removeThis' last from the act method) or you will end up throwing IllegalStateException errors.
You need to login to post a reply.