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

2019/4/12

Get the angle of an actor

ckverdad ckverdad

2019/4/12

#
boolean swingLeft = false;
    int rotation = getRotation();
    
    public void act() 
    {
        turnRate(2);
    }   
    
    public void turnRate(int xSpeed)
    {
        if (swingLeft == true)
        {
            this.turn(xSpeed);
        }
        
        else
        {
            this.turn(-xSpeed);
        }
    }
    
    public void swing()
    {
       if(rotation == -135)
       {
           swingLeft = true;
       }
       
       else if (this.getRotation() == -45)
       {
           swingLeft = false;
       }
    }
I'm trying to get the angle of an actor whose current rotation is (-45) at the start and would become (-135). The getRotation() method doesn't get the angle of the object (I think). Is there any other way or method around this to get the angle of the actor?
danpost danpost

2019/4/12

#
ckverdad wrote...
<< Code Omitted >> I'm trying to get the angle of an actor whose current rotation is (-45) at the start and would become (-135). The getRotation() method doesn't get the angle of the object (I think). Is there any other way or method around this to get the angle of the actor?
The main problem is that you get the default rotation at line 2. That line is executed when the actor is created (and field is initially declared) and the rotation is zero. To get a current rotation value, getRotation must be called within a method (either the act method or a method called during the execution of the act method). Also, it always returns a value between zero, inclusive, and 360, exclusive. Therefore, you need to compare its returned value to 315 (for -45) and 225, for (-135). That is the reason it appears not to work. A simplified class might be:
int swing = -2;

public void act()
{
    turn(swing);
    if (getRotation == 315 || getRotation == 225) swing = -swing;
}
ckverdad ckverdad

2019/4/12

#
Thanks man! The greenfoot api needs to be a little clearer in it's descriptions, nonetheless, thanks a lot!
danpost danpost

2019/4/12

#
ckverdad wrote...
Thanks man! The greenfoot api needs to be a little clearer in it's descriptions, nonetheless, thanks a lot!
Seems quite clear to me:
Return the current rotation of this actor. Rotation is expressed as a degree value, range (0..359). Zero degrees is towards the east (right-hand side of the world), and the angle increases clockwise.
Oh. and -- your welcome. Note: I just noticed I missed the parentheses after the getRotation's in my code.
You need to login to post a reply.