I have a Lava class that needs to create an enemy if you are close enough to it (using the distance formula).
My code:doesn't seem to work because the variable "distance" is always equal to 0.0
However I have to same code in another class to get the distance from the mouse pointer here:
Which works flawlessly.
Is there any specific reason that the code for Lava isn't working?
EDIT:
so I just changed the code that makes the enemies so that it creates them when the mouse is so close with this code:
This works, but I'm still unsure why the other version of the code doesn't work.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.lang.Math;
/**
* Write a description of class Lava here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Lava extends TileLoader
{
private int imgPause=0;
private int imgID=1;
private int scrllX;
private int scrllY;
public double distance=0;
public Lava(int x, int y)
{
scrllX=x;
scrllY=y;
}
/**
* Act - do whatever the Lava wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
setLocation(scrllX-Planet.scrollX, scrllY-Planet.scrollY);
imgPause++;
if(imgPause==40)
{
imgPause=0;
if(imgID==1)
{
setImage("lava2.png");
imgID=2;
}
else
{
setImage("lava.png");
imgID=1;
}
}
if(Greenfoot.getRandomNumber(10000)<1)
{
int x1=scrllX;
int x2=Planet.scrollX;
int y1=scrllY;
int y2=Planet.scrollY;
distance = Math.sqrt(Math.pow(x2-x1,2) + Math.pow(y2-y1,2));
if(distance<800.0) //the maximum distance from one corner of the visible world to another is approximately 721.11px
{
FireLobster fl=new FireLobster(scrllX,scrllY);
getWorld().addObject(fl,getX(),getY());
}
}
}
}
MouseInfo mouse = Greenfoot.getMouseInfo();
if(Greenfoot.mouseClicked(null) && mouse.getButton()==1 && mouse!=null)
{
int x1=getX();
int x2=mouse.getX();
int y1=getY();
int y2=mouse.getY();
double distance = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
if(distance<26)
{
if(canMakePopup)
{
Planet p=(Planet)getWorld();
p.popup("Would you like to enchant your weapons?","You found an enchanted bookshelf!",book);
canMakePopup=false;
}
}
}
else
{
canMakePopup=true;
}MouseInfo mouse = Greenfoot.getMouseInfo();
int x1=getX();
int x2=mouse.getX();
int y1=getY();
int y2=mouse.getY();
distance = Math.sqrt(Math.pow(x2-x1,2) + Math.pow(y2-y1,2));
if(distance<52.0) //the maximum distance from one corner of the visible world to another is approximately 721.11px
{
FireLobster fl=new FireLobster(scrllX,scrllY);
getWorld().addObject(fl,getX(),getY());
}

