This site requires JavaScript, please enable it in your browser!
Greenfoot back
Back to discussions
matthijs124
matthijs124 wrote ...

2017/11/14

Making an object move half a circle

matthijs124 matthijs124

2017/11/14

#
I am trying to make an object move half a circle. I currently have it moving in a full circle, but I can't get it to stop halfway the loop.
public class NPC extends Actor
{
    private double i = 0;
    private int xi;
    private double xd;
    private int yi;
    private double yd;

    public void act() 
    {
        i = i + 0.01;

        xd = Math.cos(i)*100;
        yd = Math.sin(i)*100;
        int xi = (int) xd;
        int yi = (int) yd;
        setLocation(xi + 200, yi + 200); 
    }

}
I add 200 to the location so it appears somewhere in the middle. I multiply the sine and cosine of i by 100 so it will not be stuck in the range of -1 <> 1. --> so it will be visible on screen. But how am I going to make it able to stop halfway the circle?
danpost danpost

2017/11/14

#
Ask what the conditions are when the half circle has been traced. One is that the y-coordinate of the actor is 200 and another is that 'yd' is negative. These two conditions are only met when the actor reaches the left-most point. You can therefore add the following line as the first line in your act method (since the entire act method is dedicated to the moving of the actor along the circumference of the circle):
if (getY() == 200 && yd < 0) return;
matthijs124 matthijs124

2017/11/14

#
Thanks. I got it working! I indeed looked for the left-most and right-most point, and came to the (indeed logical) this number (that "i" had to be) is 3.14159265359 - pi! I could know, because half of a circle's length is pi when it has a radius of 1.
You need to login to post a reply.