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

2012/4/29

Attaching an Object

al_griff al_griff

2012/4/29

#
Hey all, so I'm trying to get one of my objects to attach to another object that moves across the world. And then, once you get the first object to move (keypress) it'll detach from the second object. I've been doing a bunch of looking around to try find this, and I found the getOneIntersectingObject method, but I have no idea on how to integrate it into my code. So if you'd be able to help me out, that'd be great.
danpost danpost

2012/4/29

#
Try having the object the one attaches to control the location of the attached object. You may need to have a boolean variable in the attaching object to help reliquish control and a reference in the object attached to for the attaching object. Then, when detaching, you may need another boolean to help in the seperation process (worry about that then, if need be; but, work on the one object controlling the location of the other for now). As far as the getOneIntersectingObject method: you will use that in the object that is attached to; in its act method (or a method that the act method calls). Basically, if intersecting object of type wanted is not null, gain control of it. The code would be something like
private boolean attachedObject = null;

if (attachedObject == null && getOneIntersectingObject(AttachingObject.class) != null)
{
    AttachingObject aObj = (AttachingObject) getOneIntersectingObject(AttachingObject.class);
    aObj.setAttached(true); // need to add boolean variable and write method in AttachingObject class
    attachedObject = aObj;
}
// after the move or setLocation for 'this', add something like the following:
if (attachedObject != null) attachedObject.setLocation(getX(), getY()- 20); 
// the (-20) above is just for example, to offset the location slightly (above)
Hopefully, that should get you started.
You need to login to post a reply.