Positioning Objects Certain Distances

The title is a little bit hard to understand, so, obviously, I’ll explain.

Lets say that I have a cube and a sphere. I want the cube to be a certain distance from the sphere when I go near it.

So I move the cube towards the sphere, the cube has a ray that senses the sphere. Once the cube senses the sphere the cube gets positioned exactly 10BU on the Y axis away from the sphere. So if I used the getDistanceTo function it would read 10.

How can I do this? I think I asked a question like this before but here’s the problem, it seems easy, but to me it’s not.

For example, the cube is 5BU away from the sphere, the ray senses the sphere, I set the position of the cube to the sphere and then -10 from the y position. This should work right? Well it does, but only the world position, so -10 doesn’t make the cube move backwards, it moves the cube -10 spaces on the Y.

Here’s a diagram:

The red arrows are the local -Y axis. Green arrows is the global -Y axis. How do I make the cube move along the red lines? So in my case it’s backwards. So basically I want the cube to move backwards according to where it’s facing which is the rotation…

Any ideas?

Which local axis is the cube moving along? I’ll guess and just say it is it’s local y axis for example sake.

import bge

cube = ...
sphere = ...

if ray_hits_sphere:
    distance = cube.getDistanceTo(sphere)
    
    # a vector that describes wich way the cube is facing
    v = cube.worldOrientation[1]

    # set the size of the vector to be 10 - the current distance
    v.magnitude = 10 - distance

    # subtract from the cube's current position
    cube.worldPosition = cube.worldPosition - v

Hey Andrew, sorry for the very late reply, but I was able to just now try the script. I’ve had a lot of work to do, so that’s why it took me so long to answer…

Here is the problem, when I use the script the cube doesn’t move back 10 units, it kind of stretches back 10 units… Maybe I set it up wrong, here’s the .blend I used and your example.

example.blend (410 KB)

The problem comes from this line:

v = cube.worldOrientation[1]

A Matrix object is constructed using rows of Vector objects, that line will return a reference to the object so by altering that vector the orientation matrix is also being altered. Thats where the stretching comes from.

To solve it we just need to return a clone of the vector instead of using the original:

v = cube.worldOrientation[1].copy()

Wow, well, now it works (no surprise)

Thanks a lot Andrew, it’s really appreciated. :slight_smile: