user1762507
user1762507

Reputation: 782

How can I make a body move to the location of my touch?

Hi I am trying to make an air hockey type game but I am having trouble implementing the paddle movement component. How can I move a body(the paddle) to the location of my touch with the box2d extension for andengine using setLinearVelocity? When I try to do it the ball moves in a seemingly random path.

Here is what I've tried.

@Override
    public boolean onSceneTouchEvent(Scene pScene, TouchEvent p) {

            if(p.isActionDown()){
                moveAir(p.getY(),p.getX());
            }else if(p.isActionMove()){
                moveAir(p.getY(),p.getX());
            }else if(p.isActionUp()){
                myPad.setLinearVelocity(0, 0);
            }


        return false;
    }

    private void moveAir(float y, float x) {
        x=x/32;
        y=y/32;



        if(myPad.getLocalCenter().x>x){
            myPad.setLinearVelocity(myPad.getLinearVelocity().x-10, myPad.getLinearVelocity().y);
        }else if(myPad.getLocalCenter().x<x){
            myPad.setLinearVelocity( myPad.getLinearVelocity().x+10,  myPad.getLinearVelocity().y);
        }else{
            myPad.setLinearVelocity(0, myPad.getLinearVelocity().y);
        }


        if(myPad.getLocalCenter().y>y){
            myPad.setLinearVelocity(myPad.getLinearVelocity().x,myPad.getLinearVelocity().y-10);
        }else if(myPad.getLocalCenter().y<y){
            myPad.setLinearVelocity( myPad.getLinearVelocity().x,myPad.getLinearVelocity().y+10  );
        }else{
            myPad.setLinearVelocity(myPad.getLinearVelocity().x, 0);
        }
    }

Upvotes: 2

Views: 900

Answers (2)

user1762507
user1762507

Reputation: 782

Thanks for the suggestion but I found that using setLinearVelocity was simpler to use than a mouse joint:

float linearVelocityX = (TouchX - myBody.getPosition().x);
float linearVelocityY = (TouchY - myBody.getPosition().y);
Vector2 linearVelocity = new Vector2(linearVelocityX, linearVelocityY);
myPad.setLinearVelocity(linearVelocity);

Upvotes: 1

Plastic Sturgeon
Plastic Sturgeon

Reputation: 12527

Box2D has a special type of joint for exactly this type of interaction. You want to use a "mousejoint" on the object touched.

There is already a nice mousejoint tutorial on the andengine forum: http://www.andengine.org/forums/tutorials/tut-box2d-mousejoint-drag-and-drop-t1156.html

Upvotes: 3

Related Questions