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

2017/3/29

Need help with rotation an actor from the edge

Asiantree Asiantree

2017/3/29

#
public class Ant extends Actor
{
    private double xSpeed;
    private double ySpeed;
    
    private int goodCalorie;
    private int badCalorie;
    
    private double exactX;
    private double exactY;
    
    public Ant (double xSpeed, double ySpeed)
    {
        goodCalorie = 200;
        badCalorie = 100;
        this.xSpeed = xSpeed;
        this.ySpeed = ySpeed;
    }
    protected void addedToWorld (World myWorld)
    {
        exactX = getX();
        exactY = getY();
    }
    /**
     * Act - do whatever the Ant wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        exactX += xSpeed;
        exactY += ySpeed;
        setLocation ( (int) exactX, (int) exactY );
        if (isAtEdge()) 
        {
            setLocation( (int) exactX, (int) exactY );
        } 
        }
    }
How can I use the negative of the xSpeed and ySpeed?
Nosson1459 Nosson1459

2017/3/29

#
To switch the negativity of the x and y speeds just do xSpeed = -xSpeed which will make + be - and - be +.
Asiantree Asiantree

2017/3/29

#
I am trying to rotate the Ant when it touches the edge so it can continue moving around.
Nosson1459 Nosson1459

2017/3/29

#
Then change lines 33 - 36 to:
if (getX() <= getImage().getWidth() / 2 || getX() >= getWorld().getWidth() - (getImage().getWidth() / 2)) {
    xSpeed = -xSpeed;
}
if (getY() <= getImage().getHeight() / 2 || getY() >= getWorld().getHeight() - (getImage().getHeight() / 2)) {
    ySpeed = -ySpeed;
}
Asiantree Asiantree

2017/3/29

#
Thank you very much!
Nosson1459 Nosson1459

2017/3/29

#
I don't see why you need the exact(x/y) variables. You can remove everything that has to do with them and then change line 32 to:
setLocation((int) (getX() + xSpeed), (int) (getY() + ySpeed));
danpost danpost

2017/3/29

#
Nosson1459 wrote...
I don't see why you need the exact(x/y) variables. You can remove everything that has to do with them and then change line 32 to:
setLocation((int) (getX() + xSpeed), (int) (getY() + ySpeed));
Accuracy in position is lost due to rounding if you use that line. The way Asiantree is coding it looks to be correct for smooth movement.
You need to login to post a reply.