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

2016/12/23

problem with counter

sunshine1 sunshine1

2016/12/23

#
Hi guys, I am trying to make a game with ball and 2 gates. When the ball hits the gate it have to give one point but I can not do it even count for one gate. It doen't work . Please help me. That is the code for Counter: import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; /** * A simple counter with graphical representation as an actor on screen. * * @author mik * @version 1.0 */ public class Counter extends Actor { private static final Color transparent = new Color(0,0,0,0); private GreenfootImage background; private int value; private int target; /** * Create a new counter, initialised to 0. */ public Counter() { background = getImage(); // get image from class value = 0; target = 0; updateImage(); } /** * Animate the display to count up (or down) to the current target value. */ public void act() { if (value < target) { value++; updateImage(); } else if (value > target) { value--; updateImage(); } } /** * Add a new score to the current counter value. */ public void add(int score) { target += score; } /** * Return the current counter value. */ public int getValue() { return value; } /** * Set a new counter value. */ public void setValue(int newValue) { target = newValue; value = newValue; updateImage(); } /** * Update the image on screen to show the current value. */ private void updateImage() { GreenfootImage image = new GreenfootImage(background); GreenfootImage text = new GreenfootImage("" + value, 22, Color.BLACK, transparent); image.drawImage(text, (image.getWidth()-text.getWidth())/2, (image.getHeight()-text.getHeight())/2); setImage(image); } } reference in the subclass of World: addObject(new gate1(), 10, 200); addObject(new gate2(), 590, 200); Counter counter = new Counter(); addObject(new Counter(), 58, 26); and reference in ball class that actually public class ball1 extends Actor { /** * Act - do whatever the ball1 wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move(4); Actor gate_1 = getOneIntersectingObject(gate1.class); if (gate_1!=null) { turn(180); }
danpost danpost

2016/12/23

#
It is not enough just to have a Counter object in the world. You need collision detection between the ball and the gates and a reference to the Counter object so that you can call a method on it to adjust its value. If each gate is to score separately (not add to the same score counter), then you need a second Counter object in the world as well. If this is the case, you will need to reply for help on how to assign a counter to each gate.
You need to login to post a reply.