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

2013/4/13

How do I make an object move upwards?

h123n h123n

2013/4/13

#
This is something I've wanted to know for a long time, how do I make an object move upwards/downwards? I am making a game similar to space invaders but the enemies need to go down the screen, so my question is: "how do I do this?" if anyone can help, I'd be so thankful.
Gevater_Tod4711 Gevater_Tod4711

2013/4/13

#
If you want an object to move you have to use the setLocation method. There you can set the new location of an object. If you want your actor to move down (for example 5 cells): setLocation(getX(), getY() + 5); This makes your actor move down. If you want him to move up you use -5 instead of +5. If you want him to move right you use setLocation(getX() + 5, getY()), or -5 for moving left.
h123n h123n

2013/4/13

#
Thanks, this really helped, now I have a VERY simple game where you avoid lazer beams.
h123n h123n

2013/4/13

#
Ok, so that's done but now I'm wondering how to make my object EnergyBall work so when It's hit by a lazer the lazer teleports exactly 300 cells above the EnergyBall. In case you need code, here it is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
 
/**
 * Write a description of class EnergyBall here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class EnergyBall extends Actor
{
    /**
     * Act - do whatever the EnergyBall wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        //see if The energy ball has been hit
        Actor lazer;
        lazer = getOneObjectAtOffset(0,0, Lazer.class);
        if (lazer != null)
        {
           World world;
           world = getWorld();
           world.removeObject(lazer);
           world.addObject(new Lazer(),300, 0);
       
    }   
}
}
danpost danpost

2013/4/13

#
You need to place the new Lazer object in the world relative to the location of the EnergyBall object.
1
2
// line 25 should be
world.addObject(new Lazer(), getX(), getY()-300);
You need to login to post a reply.