ronald wrote...
<< Code Omitted >>
PendulumWorld4 oldWorld = (PendulumWorld4) getWorld(); PendulumWorld4_1 newWorld = new PendulumWorld4_1(); newWorld.setWorld(oldWorld); Greenfoot.setWorld(newWorld);
public void act() {
String key = Greenfoot.getKey();
if (key != null) {
// actions to change world size
int change = 0;
if ("up".equals(key)) change = 1;
if ("down".equals(key)) change = -1;
if (change != 0) {
int halfHeight = getHeight()/2+change;
if (halfHeight>= 100 && halfHeight<= 300) {
Greenfoot.setWorld(new MyWorld(halfHeight));
}
}
// other key related actions (preferably here)
}
}World w_new = new MyWorld(halfHeight); Pendulum_4 p_new = (Pendulum_4) w_new.getObjects(Pendulum_4.class).get(0); Pendulum_4 p_old = (Pendulum_4) this.getObjects(Pendulum_4.class).get(0); p_old.setImage(p_new.getImage()); w_new.addObject(p_old, p_new.getX(), p_new.getY()); w_new.removeObject(p_new) Greenfoot.setWorld(w_new);
import greenfoot.*;
public class MyWorld extends World
{
public static int SIZE = 300;
public static Pendulum pendulum;
public MyWorld()
{
super(SIZE*3, SIZE*2, 1);
GreenfootImage bg = getBackground();
bg.setColor(Color.BLUE);
bg.fillRect(0, 0, SIZE*3, SIZE/2);
bg.setColor(Color.GREEN);
bg.fillRect(0, SIZE*3/2, SIZE*3, SIZE/2);
if (pendulum == null) pendulum = new Pendulum();
addObject(pendulum, SIZE*3/2, SIZE/2);
}
public void act() {
int change = 0;
String key = Greenfoot.getKey();
if ("up".equals(key)) change++;
if ("down".equals(key)) change--;
if (change == 0) return;
change *= 4;
if (SIZE+change < 100 || SIZE+change > 300) return;
SIZE += change;
Greenfoot.setWorld(new MyWorld());
}
}import greenfoot.*;
public class Pendulum extends Actor
{
private double angle = Math.PI/2;
private int length;
double angleAccel;
double angleVelocity;
double dt = 0.2;
public Pendulum() {
length = MyWorld.SIZE;
GreenfootImage img = new GreenfootImage(length/5, length*11/5);
img.fillOval(length/20, length*21/20, length/10, length/10);
img.drawLine(length/10, length*11/10, length/10, length*2);
img.fillOval(0, length*19/10, length/5, length/5);
setImage(img);
}
public void act() {
angleAccel = -9.81 / length * Math.sin(angle);
angleVelocity += angleAccel * dt;
angle += angleVelocity * dt;
setRotation((int)(angle*180/Math.PI));
}
}