Wednesday, June 25, 2008

Second Life Physics Scripting - Pinball #4

I need to make the ball a little smarter when it got stuck on the lower slope. I got a little crazy and added something to try and keep it at a constant velocity of 0.42M (the size of the ball), since anything faster than this can cause it to move through a wall across a frame rate. This is the final script.

float movebump = 0.2;
float maxspeed = 0.42;
float speeddiff = 0.02;
// http://lslwiki.net/lslwiki/wakka.php?wakka=llApplyImpulse
default
{
state_entry()
{
llSetTimerEvent(1.0); // generate a timer event every 1 second
}

timer()
{
//vector ra = <llFrand(movebump),llFrand(movebump),llFrand(movebump)>;
//llOwnerSay("ball moving "+(string)ra);
//llOwnerSay("ball moving mag "+(string)llVecMag(ra));
vector vel = llGetVel();
float velmag = llVecMag(vel);

// check for anything above or below the maximum velocity
if ( (velmag>0) && ((velmag>maxspeed+speeddiff) || (velmag<maxspeed-speeddiff)))
{
//llOwnerSay("oldvelmag = "+(string)llVecMag(vel));
// need to slow or speed up the ball
float magdev = maxspeed / velmag;
vel = vel * magdev;

// take that new velocity and apply it to the ball
llApplyImpulse(llGetMass()*vel,FALSE);
//llOwnerSay("newvelmag = "+(string)llVecMag(vel));
}
else if (velmag==0)
{
// need to give it a random bump!
vector ra = <llFrand(movebump),llFrand(movebump),llFrand(movebump)>;
//llOwnerSay("ball moving "+(string)ra);
llOwnerSay("ball vel 0 move bump = "+(string)llVecMag(ra));
// give the ball a little wiggle
llPushObject(llGetKey(), ra, <0,0,0>, FALSE);
}
//llOwnerSay("ball vel "+(string)llGetVel());
// give the ball a little wiggle
//llPushObject(llGetKey(), ra, <0,0,0>, FALSE);
}
}

I think there are still problems with it, because it should have been a problem in that it would never slow down and move down the board in the way I "thought" I coded it, but it does work, but it also still gets stuck briefly. I had to add the check for 0 velocity at the end because it was getting divide by zero and that else (velmag==0) piece of code was all I really needed in the first place. I'll have to revisit it, but at least it doesn't get stuck indefinitely any longer, but it still gets stuck a lot more than I'm willing to live with.

No comments: