# Keeping an object a set distance from a surface (using Python)

Hi everyone

Just like the title, how do you keep an object a set distance from a surface (using Python)? Is it a matter of setting a z distance (if so, how?).

I ask as I’m struggling a bit with a script that was very kindly written for me from a chap from Gameblender.org. It allows objects to loop the loop, but the script renders Fh material forces inoperable. Instead, the script emulates the material force field but since it uses liner forces the object will dig into the loop as it goes round.

The latter is the part I am struggling with (in the script it is the forceoffield variable). At the moment my Python is more ‘hello world’ and this goes right over my head. From what I understand the script needs a way to calculate the linear velocites of x and y but keep z constant (or so I think).

Can anyone help?

Here is the blend:

Many thanks

Paul

### Attachments

loop.blend (391 KB)

Here’s a slightly improved version, where the second argument where you call the script will determine how far out the object stays - I put in the script that it’s BU, but actually, I can’t guarantee that (Vector magnitudes are represented another way, so I’m not so sure). In any case, increasing the second number will keep the object further away.

It subtracts the ray’s hit position by the object’s world position to get a vector representing distance and direction to the floor. After this, increasing or decreasing the magnitude works alright.

loop_distance.blend (354 KB)

To be honest, the script (and the effect) is a bit off. The cube keeps bouncing, and the effect really could be more accurate (it’s snapping to the floor even though it’s still in the air). Either the settings hold the key to the problems, or it might be a good idea to create a new script (your own) to fit your setup (and learn Python along the way).

EDIT: I initially misread the question so I’m not sure how to go about this myself, all I know is that you would get a ray sensor to get the hitNormal, then adjust the character’s position (based on his local Z-axis) and rotation based on that to keep him off of any surface.

Thanks for looking at the script: I was thinking of having a set distance before the cube aligns to the surface, which I assume would be simple using a raycast (or even a logic brick setup).

I suppose I could combine your changes with the original script which had no simulated material physics. To be honest, the author of the script left the calculation of the forceoffield open, and this held the key to the bouncing, something which is beyond my beginner Python knowledge.

I’ll post that file (the ‘clean’ version), is it a good basis or should I start over?

Cheers

Paul

### Attachments

gravitydefy_2.blend (426 KB)