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

2013/1/10

how to spawn an actor that have different speeds?

Mcstevens Mcstevens

2013/1/10

#
i've created a game where actors (Alien) move from the right side of the screen to the left. i've tried to give them different set speeds as they move across with this code: public void Speed() { int myRadNum = 0; myRadNum = Greenfoot.getRandomNumber(100); if (myRadNum < 25) { setLocation(getX()-1,getY()); } else if (myRadNum < 50) { setLocation(getX()-2,getY()); } else if (myRadNum < 75) { setLocation(getX()-10,getY()); } else setLocation(getX()-20,getY()); } but instead of moving at a set speed they change speed as they move. is there a way to give them a set speed without having multiple Alien subclasses?
Gevater_Tod4711 Gevater_Tod4711

2013/1/10

#
The problem is that you use a new random number every time the method Speed is executed. If you declare the value of the number in your constructor and don't change this value (you have to use a global variable for this) it'll work.
Mcstevens Mcstevens

2013/1/10

#
could i possibly get the code out of you?
Gevater_Tod4711 Gevater_Tod4711

2013/1/10

#
No problem.
public class Alien exdends Actor {//not sure if your class is named like this. If not change it;

int speed = 0;

public Alien() {//the constructor of the class;
    speed = Greenfoot.getRandomNumber(100);
}

public void act() {
    speed();
    //probably you got some other stuff here;
}

public void speed() { 
    if (speed < 25) {
        setLocation(getX()-1,getY()); 
    } 
    else if (speed < 50) { 
        setLocation(getX()-2,getY()); 
    } 
    else if (myRadNum < 75) { 
        setLocation(getX()-10,getY()); 
    } 
    else {
    setLocation(getX()-20,getY()); 
    } 
}
}
danpost danpost

2013/1/10

#
You need to declare an instance int field in the class to hold the speed for each object created and assign the random value (1, 2, 10, or 20) in the constructor of the object.
// declare instance int field
private int speed;
// in the constructor code
int radNum=Greenfoot.getRandomNumber(4); // 4 possibile speeds
speed=((radNum%2)+1)*((radNum/2)*9+1);
if radNum=0: radNum/2=0, *9=0, +1=1; radNum%2=0, +1=1; 1*1=1 if radNum=1: radNum/2=0, *9=0, +1=1; radNum%2=1, +1=2; 1*2=2 if radNum=2: radNum/2=1, *9=9, +1=10; radNum%2=0, +1=1; 10*1=10 if radNum=3: radNum/2=1, *9=9, +1=10; radNum%2=1, +1=2; 10*2=20 Now, in your act (or a method it calls, just use:
setLocation(getX()-speed, getY());
You need to login to post a reply.