Game Development Community

How to make a shot bounce in TGB (t2d)

by Jon Mitchell · 04/04/2007 (10:47 pm) · 0 comments

First things first, make sure the objects you want your shot to collide with have their collision properties set to send collisions, and also have the layer(s) you want it to look for selected. In this example my shot resides in layer 5 my static objects that the shot will bounce off from resides in layer 3 and has a class name of "terrain". So my terrain object would be looking for something on layer 5 and my shot will be looking for something on layer 3.

In my function to launch the ball I have the following bit of code to set collision properties for the ball, this sets layer it will reside in and the layer to watch for in case of a collision as well as the collision properties.

%ball.setCollisionActive( true, true );
%ball.setCollisionPhysics(false, true);
%ball.setCollisionCallback(true);
%ball.setLayer(5);
%ball.setCollisionLayers(3);

I will not dive into the details and properties on this bit of code here, if you would like to know more or for details on .setCollisionActive, Physics and callBack, please visit the TDN reference TGB/Reference: t2dSceneObject Collision Methods That is where I found the references originally and they are very straight forward.


Now for the point of the matter, simple and quick code for bounces.

//This function happens when the ball touches something in a layer it is set to watch for
function playerball::onCollision( %srcObj, %dstObj, %srcRef, %dstRef, %time, %normal, %contactCount, %contacts )
{

//We check to see if the object in layer 3 has a class name of "terrain"
if(%dstObj.class $= "terrain")
{

//Here if the object was terrain we want to do something, there are many options we could do. We could //make the ball explode or just simply remove it from the game, but in this case we want it to bounce
//This will cause the ball to bounce off at the same speed it made contact with and at an appropriate angle
%srcObj.setCollisionResponse(bounce);
}
}


For more information on setCollisionResponse I recommend you visit TDN's reference guide and look up setCollisionResponse and take a look at the options available to you.

As I mentioned a few times, this is a really basic way to get something to bounce, if you want more there are many good references out there for bounce with physics out there if you do a search.