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

2015/1/16

Multiple image movement

Mrinal Mrinal

2015/1/16

#
Hi! So this is a program where there is are ladybugs at diagonal opposite corners of the world. They are facing each other. The two ladybugs are two different images stored in the same class titled "Ladybug" . Now, when i press right arrow key, I want the ladybug in the bottom corner to move right and the one in the top corner to move left. When i press left arrow key, the bottom one moves left and the top one moves right. Similar way for up and down. basically, the bottom one follows the arrow keys and the top one does the exact opposite. It has something to do with parameters im' guessing but I cant figure it out. Help needed urgently. For more reference, there's the image of the world. Thanks!
Super_Hippo Super_Hippo

2015/1/16

#
You could control the moving in the world subclass:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// outside methods
Ladybug l1,l2;
 
// when creating the world
l1 = new Ladybug();
l2 = new Ladybug();
addObject(l1,0,getHeight());
addObject(l2,getWidth(),0);
 
// in the act method or in some method which is called from the act method
int dx=0,dy=0;
if (Greenfoot.isKeyDown("up") dy--;
if (Greenfoot.isKeyDown("down") dy++;
if (Greenfoot.isKeyDown("left") dx--;
if (Greenfoot.isKeyDown("right") dx++;
 
if (dx != 0 || dy != 0)
{
    l1.setLocation(l1.getX()+dx,l1.getY()+dy);
    l2.setLocation(l2.getX()-dx,l2.getY()-dy);
}
Mrinal Mrinal

2015/1/17

#
Works perfectly Thanks! :) One little problem. How do I get the ladybug in the top corner to face left at startup? Like when I press compile, the bottom one faces right, but the top one too faces right. That's something i want to change...
danpost danpost

2015/1/17

#
Mrinal wrote...
Works perfectly One little problem. How do I get the ladybug in the top corner to face left at startup?
At line 9 above in the code Super_Hippo supplied:
1
l2.setRotation(180);
Mrinal Mrinal

2015/1/17

#
Alrighty! Thanks a lot! :D
Mrinal Mrinal

2015/1/18

#
Oh.. Just another doubt. What is the code I have to put in the LADYBUG CLASS to make the ladybug move in the same way as it worked above as posted by Super_Hippo... ?
danpost danpost

2015/1/18

#
If you were to code it in the Ladybug class, you would need a field to distinguish one from the other as far as which direction they will move. An int type field would be easiest in this case. One instance can have a value of '1' while the other has a value of '-1'. Then multiply both value parameters in the 'setLocation' statement by the field.
You need to login to post a reply.