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

2015/5/19

A little help with intersects() method

NoValidIdea NoValidIdea

2015/5/19

#
Hello, I'm trying to do the PongTable game and i'stuck with the intersects() method. I know there are other ways to do this but i want to understand my mistake. Method signature is: intersects(Actor other). What is the correct syntax in my case. I want to call the method from here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Ball extends Actor
{
    private int vSpeed;
    private int hSpeed;
    int margin = getImage().getWidth()/2;
     
    public Ball (int speed) {
        vSpeed = speed;
        hSpeed = speed;
        
    }
    
    public void act()
    {
        move();
        if (intersects(?????????)) {
            //do something
        }
    }
The object i want to call is the Paddle:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Paddle extends Actor
{
    public static final int WIDTH = 100, HEIGHT=20, SPEED=5;
    public int hits;
     
    public Paddle () {
         
        GreenfootImage img = new GreenfootImage (WIDTH, HEIGHT);
        img.fillRect (0, 0, WIDTH, HEIGHT);
        setImage (img);
        hits =0;
         
    }
    
    public void act()
    {
        movePaddle();
        }
The Constractor is in the World class: public class PongTable extends World { public static final int SPEED = 5; public PongTable() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(500, 600, 1); addObject(new Paddle(), 250, 550); addObject(new Ball(SPEED), 250, 270); } } The error i get when i write something like: (intersects(Paddle)) is intersects(greenfoot.Actor) in greenfoot actor cannot be applied to .... Sorry if thats to much code for a small problem. Thank you in advance.
danpost danpost

2015/5/19

#
The 'intersects' method requires an Actor object for its parameter, not a class name. That is, you need to supply which actor object you wish to check intersection with. If you are sure there is always one, and only one, paddle in the world, you could use this:
1
if (intersects((Actor)getWorld().getObjects(Paddle.class).get(0)))
However, better might be to hold a reference to the Paddle object in your world subclass:
1
2
3
4
5
// instance field
public Paddle paddle; // to hold reference to Paddle object
// in constructor
paddle = new Paddle(); // saves reference to paddle in field
addObject(paddle, 250, 250);
Then, your code might be:
1
2
Paddle paddle = ((PongTable)getWorld()).paddle;
if (intersects(paddle))
You could make the instance field 'private' access and add a 'public getter' method to allow the ball to get the paddle reference.
NoValidIdea NoValidIdea

2015/5/19

#
Thanks. The reference soulution is way better...
You need to login to post a reply.