Collision

How do you check movement collisions, I’ve got some nice-looking objects but I can just “fly” with my camera through them, and through my floor too. Does anyone know good tutorials/samples?

Sneak-preview :smiley:

You managed to make this in Java but you have no idea of collision detection?

A plan:

  • Try to make your own.
  • Realise its too hard.
  • Use JBullet! Its easy.

If you want to roll your own, make yourself ready for a heck-load of math, physics, and linear algebra.
Seriosly, just go and use JBullet for collision detection and handling.
It makes your life a lot easier.

Have a nice day!

  • Longor1996

PS: I can’t see the image. It’s WAY too big for my internet connection (0-64 Bit per Second).

Thanks for the advice :D, I’ll look for JBullet.

Either a physics library, or write code to handle sphere/sphere collisions, and compose a tight fitting bounding volume around your objects using a bunch of (never rendered) spheres. Then you can proudly bump into your trees.

What is the best way to translate my VBO which I load in LWJGL to a CollisionShape of the JBullet library?

That’s the most vague request ever. What is a CollisionShape? Are you using a library? What have you tried? What is the problem?

I load objects from a Wavefront (.OBJ) file, and create a model of them.


    // List of vertices
    private List<Vector3f> vertices;
    // List of normals
    private List<Vector3f> normals;
    // List of faces
    private List<Face> faces;

I want to create a CollisionShape in the JBullet library for this object. What would be the best way to do this? I can’t even find an idea how to do this.

Did you follow theCodingUniverse’s tutorials to do this? If you did, I know he also had tutorials on JBullet.

I’ve got it a bit working, but it’s reallllly glitchy:


    public static CollisionShape modelToShape(ObjectArrayList<Vector3f> points) {
    	CollisionShape shape = new ConvexHullShape(points);
    	return shape;
    }


    public static RigidBody createRigidBody(CollisionShape shape, float mass, float restitution, Vector3f pos, Vector3f rotation) {
        DefaultMotionState motionState = new DefaultMotionState(new Transform(new Matrix4f(new Quat4f(rotation.x, rotation.y, rotation.z, 1), new Vector3f(pos.x, pos.y, pos.z), 1)));
        Vector3f inertia = new Vector3f();
        shape.calculateLocalInertia(mass, inertia);
        RigidBodyConstructionInfo constructionInfo = new RigidBodyConstructionInfo(mass, motionState, shape, inertia);
        constructionInfo.restitution = restitution;
        RigidBody body = new RigidBody(constructionInfo);
        body.setCollisionFlags(CollisionFlags.STATIC_OBJECT);
        return body;
    }

But the floor is everywhere the same height and it doesn’t work at all with the trees.

He has a tutorial on JBullet, but it doesn’t really cover that, I don’t think.

EDIT: I was horribly wrong.

    public static CollisionShape modelToShape(List<Vector3f> vertices, List<Face> faces) {
    	float[] coords = new float[vertices.size()*3];
    	for(int n = 0; n < vertices.size(); n++) {
    		Vector3f f = vertices.get(n);
    		coords[n*3] = f.x;
    		coords[n*3+1] = f.y;
    		coords[n*3+2] = f.z;
    	}
    	int[] indices = new int[faces.size()*3];
    	for(int n = 0; n < faces.size(); n++) {
    		Face f = faces.get(n);
    		indices[n*3] = (int) f.getVertex().x;
    		indices[n*3+1] = (int) f.getVertex().y;
    		indices[n*3+2] = (int) f.getVertex().z;
    	}
	
		if (indices.length > 0) {
			IndexedMesh indexedMesh = new IndexedMesh();
			indexedMesh.numTriangles = indices.length / 3;
			indexedMesh.triangleIndexBase = ByteBuffer.allocateDirect(indices.length*4).order(ByteOrder.nativeOrder());
			indexedMesh.triangleIndexBase.asIntBuffer().put(indices);
			indexedMesh.triangleIndexStride = 3 * 4;
			indexedMesh.numVertices = coords.length / 3;
			indexedMesh.vertexBase = ByteBuffer.allocateDirect(coords.length*4).order(ByteOrder.nativeOrder());
			indexedMesh.vertexBase.asFloatBuffer().put(coords);
			indexedMesh.vertexStride = 3 * 4;
	
			TriangleIndexVertexArray vertArray = new TriangleIndexVertexArray();
			vertArray.addIndexedMesh(indexedMesh);
	
			boolean useQuantizedAabbCompression = true;
			BvhTriangleMeshShape meshShape = new BvhTriangleMeshShape(vertArray, useQuantizedAabbCompression);
			
			return meshShape;
		}
    	
    	return null;
    }

I’m getting this stack trace:

Exception in thread "main" java.lang.IndexOutOfBoundsException
	at java.nio.Buffer.checkIndex(Unknown Source)
	at java.nio.DirectByteBuffer.getFloat(Unknown Source)
	at com.bulletphysics.collision.shapes.ByteBufferVertexData.getVertex(ByteBufferVertexData.java:58)
	at com.bulletphysics.collision.shapes.VertexData.getTriangle(VertexData.java:53)
	at com.bulletphysics.collision.shapes.StridingMeshInterface.internalProcessAllTriangles(StridingMeshInterface.java:51)
	at com.bulletphysics.collision.shapes.StridingMeshInterface.calculateAabbBruteForce(StridingMeshInterface.java:78)
	at com.bulletphysics.collision.shapes.BvhTriangleMeshShape.<init>(BvhTriangleMeshShape.java:76)
	at com.bulletphysics.collision.shapes.BvhTriangleMeshShape.<init>(BvhTriangleMeshShape.java:63)
	at tk.Kefwar.OpenGL.Physics.modelToShape(Physics.java:117)
	at tk.Kefwar.OpenGL.model.Model.prepareVBO(Model.java:257)
	at tk.Kefwar.OpenGL.model.Model.loadOBJModel(Model.java:187)
	at tk.Kefwar.OpenGL.model.Scenario.loadObjects(Scenario.java:84)
	at tk.Kefwar.OpenGL.model.Scenario.<init>(Scenario.java:21)
	at tk.Kefwar.OpenGL.Main.init(Main.java:37)
	at tk.Kefwar.OpenGL.util.Game.gameLoop(Game.java:77)
	at tk.Kefwar.OpenGL.util.Game.<init>(Game.java:37)
	at tk.Kefwar.OpenGL.Main.<init>(Main.java:14)
	at tk.Kefwar.OpenGL.Main.main(Main.java:142)

Anyone knows what I’m doing wrong?

No one is going to help unless you are more specific and show effort yourself. You have an index out of bounds exception, go ahead and try to figure out what’s going out of bounds. Simple debugging.

I got the code above working, by just increasing vertices.size() *3 to vertices.size() *4. And it works.

Hopefully you know why?

I have been implementing this to my game, and I discovered a problem: My character was rolling off the hills when I used a RigidBody as camera/character. I have searched a lot and saw about the KinematicCharacterController. After several attempts and failures I don’t get it working.
Main source I’ve used: http://stackoverflow.com/questions/18405592/jbullet-kinematic-objects.

My CharacterController class:


package tk.Kefwar.OpenGL.Physics;

import javax.vecmath.Vector3f;

import tk.Kefwar.OpenGL.model.Texture;

import com.bulletphysics.collision.broadphase.CollisionFilterGroups;
import com.bulletphysics.collision.dispatch.CollisionFlags;
import com.bulletphysics.collision.dispatch.GhostObject;
import com.bulletphysics.collision.dispatch.PairCachingGhostObject;
import com.bulletphysics.collision.shapes.ConvexShape;
import com.bulletphysics.dynamics.DynamicsWorld;
import com.bulletphysics.dynamics.RigidBody;
import com.bulletphysics.dynamics.RigidBodyConstructionInfo;
import com.bulletphysics.dynamics.character.KinematicCharacterController;
import com.bulletphysics.linearmath.Transform;

public class CharacterController {
	private DynamicsWorld world;
    private MyMotionState myMotionState;
    private RigidBody rigidBody;
    private KinematicCharacterController character;
    private ConvexShape shape;
    private PairCachingGhostObject ghost;
    private Vector3f pos;
    
    public CharacterController(DynamicsWorld world, Vector3f initialPosition, ConvexShape shape, MyMotionState myMotionState) {
    	this.pos = initialPosition;
        this.world = world;
        RigidBodyConstructionInfo constructInfo = new RigidBodyConstructionInfo(50.0f, myMotionState, shape);
        this.myMotionState = myMotionState;
        rigidBody = new RigidBody(constructInfo);
        ghost = new PairCachingGhostObject();
        ghost.setCollisionShape(shape);
        ghost.setCollisionFlags(CollisionFlags.CHARACTER_OBJECT);
        character = new KinematicCharacterController(ghost,shape,1);
        world.addCollisionObject(ghost, CollisionFilterGroups.CHARACTER_FILTER, (short)(CollisionFilterGroups.STATIC_FILTER | CollisionFilterGroups.DEFAULT_FILTER));
        world.addAction(character);
    }
    public void move(float dx, float dy, float dz, float yaw, float pitch) {
        pos.z += dx * (float) Math.cos(Math.toRadians(yaw)) + dz *        Math.cos(Math.toRadians(yaw));
        pos.x -= dx * (float) Math.sin(Math.toRadians(yaw)) + dz * Math.sin(Math.toRadians(yaw));
        pos.y += dy * (float) Math.sin(Math.toRadians(pitch)) + dz * Math.sin(Math.toRadians(pitch));
        //pseudocode
        Transform transform = new Transform();
        transform.origin.set(pos.x, pos.y, pos.z);
        rigidBody.setWorldTransform(transform);
    }
    public Vector3f getPosition() {
    	return pos;
    }
}

But now I come to my question: I’m back to the start of the thread, when I move this object, it doesn’t check for collision and gravity isn’t working anymore. What am I doing wrong?

I think the thing with the rolling can be stopped by:
character.setAngularMovement( 0 );

The rolling was when using a RigidBody and synchronise the camera position with that body and not a KinematicCharacterController of the code I posted. With the controller physics don’t work at all for me.

To say you have quite a high rank your not very observant. He quite clearly states what he’s having trouble with

Everybody makes mistakes. No need to rub it in. :point: