Make a body follow the mouse in Processing

Discuss issues specific the Java port of Box2D
dimitros
Posts: 1
Joined: Tue Apr 21, 2015 9:54 am

Make a body follow the mouse in Processing

Postby dimitros » Tue Apr 21, 2015 10:19 am

Hello, i am really struggling to make a body follow the mouse position. I really read and tried many things from the documentation, online examples etc.
I am creating a physics world and a body in it. I want to make the object always follow the mouse position but i see there is no method helping this. There are only methods for applying forces, impulse and initialization of the body.
I read and tried things like creating mouseJoint but i was not able to have a successful result.
I am wondering if i need to destroy the object and create a new one every time.
Here is what i am trying:

import shiffman.box2d.*;
///Import libraries relating to Box2D Physics engine
import org.jbox2d.util.nonconvex.*;
import org.jbox2d.dynamics.contacts.*;
import org.jbox2d.testbed.*;
import org.jbox2d.collision.*;
import org.jbox2d.common.*;
import org.jbox2d.dynamics.joints.*;
import org.jbox2d.p5.*;
import org.jbox2d.dynamics.*;

Physics physics;

Body rabbit_body; //my body
PImage bg;
PImage rabbit; //image following my body

void setup()
{
size(800, 800);
imageMode(CENTER);

rabbit = loadImage("hopr.gif");
bg = loadImage("grass.jpg");

//Set up the physics world
physics = new Physics(this,
width, height,
0, 0,
width*2, height*2,
width, height,
100);

///Set up my physics object
physics.setDensity(500.0);
rabbit_body = physics.createRect(100, 100, 120,180);
}

void draw()
{
background(bg);

Vec2 screenBallPosition = physics.worldToScreen(rabbit_body.getWorldCenter());
float ballAngle = physics.getAngle(rabbit_body); ///Returns the angle in degrees

//make the image always follow the body
pushMatrix();
translate(screenBallPosition.x, screenBallPosition.y);
rotate(-radians(ballAngle));
image(rabbit,0,0,100,100);
popMatrix();

}

What i tried is the below line:
rabbit_body = physics.createRect(mouseX, mouseY, 120,180);
But is not working. I tried to put the line in the draw function or in the mousePressed but it's crashing.

Return to “Java”



Who is online

Users browsing this forum: Google [Bot] and 3 guests