Friday, June 20, 2008

Second Life Physics Scripting - Pinball

I have been continuing to learn Linden Scripting Langage (lsl) in Second Life. I was stuck for a while on a board game and 2d video game idea and decided to move on to something else. My latest round of work has been learning the physics engine. I've been doing this by building a pinball machine.



The basics of this are in the collision_start method in the backwall of the pinball machine. The ball is a simple sphere with physics turned on.

default
{
collision_start(integer total_number)
{
//llOwnerSay(llDetectedName(0) + " collided with me!");
if (llDetectedName(0) == "ball")
{
// need to find the direction from the backwall to the ball
vector pos = llGetPos();
list a = llGetObjectDetails(llDetectedKey(0), ([OBJECT_POS]));
vector pos2 = llList2Vector(a,0);

// subtract the two positions to find the direction from the wall to the ball
vector pos3 = pos2-pos;
//llOwnerSay("pos = "+(string)pos+" pos2="+(string)pos2);
//llOwnerSay("pos3 = "+(string)pos3);

// do some multiplication to get a big bounce
pos3.x = pos3.x*4;

// change the y direction in minute ways to create a random bounce
integer ra = (integer) llFrand(1.0)-1;
pos3.y = pos3.y*ra;

// push the ball in that direction
llPushObject(llDetectedKey(0), pos3, <0,0,0>, FALSE);
}
}
}

This failed miserably since the ball kept leaping off the table. After a lot of reading it turns out that the collision system in second life only does detection on each frame so if the ball is moving fast it will be across the wall between frames and you have to go hunting for the ball. I'll discuss solutions in upcoming posts.

No comments: