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

2022/5/25

I need help pls

OE51 OE51

2022/5/25

#
this is my code, I have to make the fish move diagonally and make it reflect off edges which it does except the top edge of the world. Heres my code so far: public void turnAtEdge(){ if(isAtEdge()){ int t=getRotation(); int u=360-t; //setRotation(u); getRotation(); int x=getX(); int y=getY(); if (x>=0 ||x==getWorld().getWidth()){ int u2=270-u; setRotation(u2); }else if(y==0){ //int u3=u-210; //turn(u3); setRotation(u-120); } else{ setRotation(u); } move(2); }
OE51 OE51

2022/5/25

#
the rotation of the fish was set to 60 degrees.
Spock47 Spock47

2022/5/25

#
The problem is probably the check "x>=0 ||x==getWorld().getWidth()". The first part checks whether x is greater or equal 0, which is always true. But I think you want to check whether x is less or equal. Note, that you need two simple ideas as the basis for the reflecting: 1. If the fish bounces off top or bottom, its new rotation is 360-oldValue. 2. If the fish bounces off left or right, its new rotation is 180-oldValue. A simple source code to implement this:
    public void turnAtEdgeAndMove() {
        int x = getX();
        if (x <= 0 || x >= getWorld().getWidth() - 1) {
            setRotation(180 - getRotation());
        }
        int y = getY();
        if (y <= 0 || y >= getWorld().getHeight() - 1) {
            setRotation(360 - getRotation());
        }
        move(1);
    }
Advanced hint: Did you recognize that the fish only reflects when its center is at the edge, which means that at the time of reflection, half of the fish is already outside of the world? You can improve this by adding a "buffer" at the edges to reflect earlier, e.g.
        final int xBuffer = image.getWidth() / 2 - 1;
        int x = getX();
        if (x <= xBuffer || x + xBuffer >= world.getWidth() - 1)
Live long and prosper, Spock47
You need to login to post a reply.