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

2020/4/23

What is wrong with my code?

macaroon72 macaroon72

2020/4/23

#
This is supposed to be a visual where the leaves flutter/fall down from the tree/sky. I do not understand why my code compiles correctly, but no leaves appear on the world or fall when I hit run. Can you help me? Thanks! This is the Actor (leaf's) code... import greenfoot.*; public class Leaf extends SmoothMover { private static int NumLeaves; private int timer = ((int)(Math.random()*901)+100); private double dx; private boolean fallingRight; private int x = ((int)(Math.random()*2)+1); public Leaf() { setImage((Math.random()*4)+"Leaf1().png"); setRotation((int)(Math.random()*360)); if(x==1) { fallingRight = true; } else if (x==2) { fallingRight=false; } NumLeaves++; } public void act() { timer--; if(timer<=0) { setLocation(getX()+dx/2, getY() + 5 - Math.abs(dx) / 4); if(fallingRight ==true) { dx++; if(dx>20) { fallingRight=false; } } else { dx--; if(dx<-20) { fallingRight=true; } } if(getY()>600) { NumLeaves--; getWorld().removeObject(this); } } } public static int getNumLeaves() { return NumLeaves; } public static void reset() { NumLeaves = 0; } } ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This is the World's (Tree's) code... import greenfoot.*; public class Tree extends World { public Tree() { super(1000, 750, 1); Leaf.reset(); } public void addNumLeaves() { Leaf leaf = new Leaf(); int x = ((int)(Math.random()*801)+100); int y =((int)(Math.random()*401)); addObject(new Leaf(), x, y); } public void addLeaves( int amount ) { for(int num = 0; num<=amount; num++) { addNumLeaves(); } } public void increaseLeavesTo( int amount ) { while(Leaf.getNumLeaves()<amount) { addNumLeaves(); } } }
danpost danpost

2020/4/23

#
A method needs to be called to execute and that calling line need to be executed to perform that calling. A method will not run just because you added it into your code. I am referring to your Tree class methods.
macaroon72 macaroon72

2020/4/23

#
Can you please show me what you mean?
danpost danpost

2020/4/23

#
macaroon72 wrote...
Can you please show me what you mean?
Right click your world background and select addLeaves and enter some number. Reset and do it again. Get an idea of what number of leaves you would like to start with. When satisfied, invoke the Save the world function. Then look at the code produced in your Tree class.
macaroon72 macaroon72

2020/4/24

#
Okay, thank you!
You need to login to post a reply.