I've got a ufo beam actor in my world, and I would like it so when I press the "space" key, the image is displayed, sort of like an on and off switch.
When you press on space, the actor appears, when you press on space again the actor disappears, how would I do this?
Here is my code that is displaying my actor(s) in the world (world class):
Here is my code for the actor I want to appear and disappear every time space is pressed:
I know I would need to create an if statement to use the space key, but I just do not know where to put it, and what code should be in it.
(I'm still at a beginner level of knowledge, keep that in mind)
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class MyWorld here. * * @author (------------) * @version (a version number or a date) */ public class MyWorld extends World { /** * Constructor for objects of class MyWorld. * */ public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(700, 500, 1); // Adjusting the size of the image so it scales exactly to the world GreenfootImage bg = new GreenfootImage("Flat Terraria Landscape.jpg"); bg.scale(getWidth(), getHeight()); setBackground(bg); martianSaucer(getWidth()/2, getHeight()/10); ufoBeam(347, getHeight()/2); //backgroundMusic(); } public void martianSaucer(int width, int height) { MartianSaucer msPlacement = new MartianSaucer(); addObject(msPlacement, width, height); } public void ufoBeam(int width, int height) { UFOBeam ufoBeamPlacement = new UFOBeam(); addObject(ufoBeamPlacement, width, height); } public void backgroundMusic() { GreenfootSound backgroundMusic = new GreenfootSound("Martian Madness.mp3"); backgroundMusic.setVolume(15); backgroundMusic.playLoop(); } }
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class UFOBeam here. * * @author (your name) * @version (a version number or a date) */ public class UFOBeam extends Actor { /** * Act - do whatever the UFOBeam wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public UFOBeam() { GreenfootImage image = getImage(); image.scale(70, 350); setImage(image); } public void act() { movingWithArrows();// Add your action code here. } public void movingWithArrows() { int x = getX(); if(Greenfoot.isKeyDown("left")) { move(-3); } if(Greenfoot.isKeyDown("right")) { move(3); } } }