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

2012/12/30

How do you grab an object?

mike123 mike123

2012/12/30

#
Me again... While i sort my rotation out, i also have another scenario... How do i go about 'grapping' an object. The bit that i am actually mostly stuck on is the grabbing. this would need to allow Actor 1 to pick up Actor 2 while a key is depressed. I am good with all the key depressing code etc, i just need to work out the actual movement code. Thanks for your help!
nooby123 nooby123

2012/12/30

#
If you want a smooth movement :
double dx, dy;    

public void act() {
    ActorA a = (ActorA)getOneIntersectingObject(ActorA.class);

    if(a.getX() > getX()) dx = (Math.abs(getX() - a.getX())/5);
    else dx = ((Math.abs(a.getX() - getX())*-1)/5);
    if(a.getY() > getY()) dy = (Math.abs(getY() - a.getY())/5);
    else dy = ((a.getY() - getY())/5);       

    setLocation(getX() + (int)dx, getY() + (int)dy);
}

ActorA is the actor you want to move towards. Put this in the actor you want to move.
danpost danpost

2012/12/30

#
I would think it would be similar to the code that allows the mouse to drag-n-drop an object. Below, I modified mouse-dragging code to produce what code should work fo you (using key 'g' for grabbing):
/* add an instance Actor field to the Actor1 class */
private Actor actorGrabbed = null;

/* in the 'act' method in the Actor1 class */
// check for initial pressing down of key
if (Greenfoot.isKeyDown("g") && actorGrabbed == null && getOneIntersectingObject(Actor2.class) != null)
{
    // grab the object
    actorGrabbed = (Actor) getOneIntersectingObject(Actor2.class);
    // the rest of this block will avoid the grabbed object from being hidden UNDER the Actor1 objects
    getWorld().removeObject(actorGrabbed);
    getWorld().addObject(actorGrabbed, getX(), getY());
}
// check for actual dragging of the object after moving Actor1 object
if (Greenfoot.isKeyDown("g") && actorGrabbed != null)
{
    // drag the grabbed object
    actorGrabbed.setLocation(getX(), getY());
}
// check for key release
if (!Greenfoot.isKeyDown("g") && actorGrabbed != null)
{
    // release the object
    actorGrabbed = null;
}
mike123 mike123

2012/12/31

#
thanks guys :)
You need to login to post a reply.