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

2012/12/30

How to you rotate an object to face another object?

mike123 mike123

2012/12/30

#
Hi How can i rotate an object to face another object, it is to be placed as the outcome of an if statement. So if object b is.... turn object b to face object a? Thanks for your help!
nooby123 nooby123

2012/12/30

#
Here, alot of people has been asking that. First have a public x and y coordinate of the actor(let's call it ActorA) you want to rotate the object to.
static int x, y;

public void act() {
    x = getX();
    y = getY();
}
Then in the object you want to rotate it towards ActorA :
// put the coordinates of the object you want to turn to
public int point_to(int x, int y) {
        int dx = x - getX(); 
        int dy = y - getY(); 
        double rotation = Math.atan2(dy, dx); 
        rotation = Math.toDegrees(rotation); 
        return (int)rotation; 
    } 

public void act() { 
        setRotation(point_to(ActorA.x, ActorA.y));
}
mike123 mike123

2012/12/30

#
Thanks for he quick reply! In your line 11, with '.x' i get the error x is not public in greenfoot.actor; cannot be accessed from outside package? any ideas?
danpost danpost

2012/12/30

#
There is already an Actor class method that does this. In the Actor B class code:
turnTowards(ActorA.getX(), ActorA.getY());
If in the world class code:
ActorB.turnTowards(ActorA.getX(), ActorA.getY());
nooby123 nooby123

2012/12/30

#
There has to be a set of static coordinates in the ActorA. As mentioned in the above code, it says :
static int x, y;
This is in the ActorA, and not in the one that you want it to rotate to.
mike123 mike123

2012/12/30

#
Thanks again for the quick reply, i have inserted the top one into my if statement but upon compiling i get: non static method getX() cannot be refrenced form a static content Any ideas? Thanks for the help!
danpost danpost

2012/12/30

#
mike123 wrote...
Hi How can i rotate an object to face another object, it is to be placed as the outcome of an if statement. So if object b is.... turn object b to face object a? Thanks for your help!
What class do you have this 'if object b is.... turn object b to face object a' code in and what code do you have in the method that statement occurs in? (by 'ActorA' and 'ActorB', I am refering to objects, not classes)
mike123 mike123

2012/12/30

#
Sorry, didnt see your post nooby, trying it now
mike123 mike123

2012/12/30

#
and yours danpost :)
mike123 mike123

2012/12/30

#
hi
public void act(){ 
      if (BinBump())
        {  
            turnTowards(lorry.getX(), lorry.getY());
         }  
        }
Does that makes sense? Im still quite new to this.
danpost danpost

2012/12/30

#
Do you have a reference to an Actor named 'lorry' declared in the class? What is the code to the 'BinBump()' method?
You need to login to post a reply.