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

2018/7/28

Greenfoot Freezing after a few seconds.

strange_Robotics strange_Robotics

2018/7/28

#
So I've had this problem with the program freezing after a few seconds of starting to run it. Every thing works fine until after a few shots all movement and input stop altogether. It's not crashing or anything, it is still running, but nothing is moving and it seems that all input is futile. This only appeared to start to happen after I tried to animate my gun. I'll put the code down for the gun class under this, maybe that is the reason for the freeze. Please point out if I did something wrong.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Gun here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Gun extends Actor
{
    private int fireDelay;
    private int animDelay;
    public int ammoCount;
   //I haven't implemented this yet, it may be the reason
    GreenfootImage image1, image2;
    /**
     * Act - do whatever the Gun wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    { 
        shoot();
        move();
        animateShot();
    }  
    public void shoot()
    {
        fireDelay--;
        if(Greenfoot. isKeyDown("space") && fireDelay <= 0)
       {
          getWorld().addObject(new Bullet(), getX()+30, getY()-10);
          //Greenfoot.playSound("tank.wav");
          fireDelay = 50;
       }  
    }
    public void move()
    {
        if (Greenfoot.isKeyDown("w"))
        {
            setLocation(getX(), getY()-8);
        }
        if (Greenfoot.isKeyDown("s"))
        {
            setLocation(getX(), getY()+8);
        }
    }
    public void animateShot()
    {
        image1 = new GreenfootImage ("ready.png");
        image2 = new GreenfootImage ("shoot.png");
        if (Greenfoot.isKeyDown("space") && animDelay >= 50)
        {
           setImage(image2);
           animDelay = 0;
        }
        else 
        {
            setImage(image1);
            animDelay++;
        }
    }
}
danpost danpost

2018/7/28

#
strange_Robotics wrote...
Please point out if I did something wrong. << Code Omitted >>
I do not see anything that would cause the scenario to "freeze" as you suggest. I do, however see something that could (potentially) cause a lagging issue (if you happen to have lots of little CPU time-wasting code as shown here). You are creating your images every act cycle (see animateShot method). You can create them once when you declare the fields, replacing line 15 with:
GreenfootImage image1 = new GreenfootImage ("ready.png");
GreenfootImage image2 = new GreenfootImage ("shoot.png");
Then you can remove lines 49 and 50.
You need to login to post a reply.