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

2012/3/16

addObject within a set Distance, using vectors

matt.milan matt.milan

2012/3/16

#
Pre-existing classes: SmoothMover, Vector i want to use a combination of vector and smoothmover to take a starting position (x,y), then add an object in a random direction, but at a set distance then i want to repeat, replacing the original position with the position of the last object added. the result would be a winding (or completely random) chain of objects each the same distance away from the last one
    public Space()
    {
        super(960, 620, 1, false);

        myShip = new SpaceShip(20, 8, new Vector(0,1.0));
        addObject(myShip, getWidth() / 2, getHeight() / 2);

        vtr = new Vector((double)myShip.getX(),(double)myShip.getY());
        vtr.setDirection(Greenfoot.getRandomNumber(359));

        spaceOutPlanets();
    }

    public void spaceOutPlanets()
    {
        for (int i = 0; i < 5; i++)
        {
            addObject(new Planet()
                (int)vtr.getX(),(int)vtr.getY());
            updateVtr();
        }
    }

    public void updateVtr()
    {
        vtr.setDirection(Greenfoot.getRandomNumber(359));
	
    }
this is a sample of the code, snipped for clarity. cycling reset about 10 times, i see situations like 1 planet but it's far, 2 planets and one is almost where i want it, but the 2nd is really far away, or no planets at all. I'm pretty sure i'm using vector wrong, my math is weak and this is a new concept for me. i'm not asking anyone to write my code ;) just, if they could, point out the obvious error i'm not seeing. in the meantime i'll be plugging away. if i figure it out, i'll repost.
davmac davmac

2012/3/17

#
Working on the assumption that you want 'vtr' to represent the distance and direction that you want to place a planet from myShip, then, there are a few lines that look wrong to me: 18. addObject(new Planet() 19. (int)vtr.getX(),(int)vtr.getY()); You're not adding the ship's co-ordinates the vector; it should be more like: addObject(new Planet() (int)vtr.getX() + myShip.getX(),(int)vtr.getY() + myShip.getY()); And with this: 08. vtr = new Vector((double)myShip.getX(),(double)myShip.getY()); ... is setting the vector size and direction dependent on the current location of 'myShip', which doesn't seem like what you want - try a vector with fixed size.
You need to login to post a reply.