user10968767
user10968767

Reputation:

Keep an object moving along the Y axis appear stationary at a point by moving its X and Z position

I need that the camera sees an object in the initial position after moving it on Y axis. I use some images to explain myself better. This is the initial position of the object. The main camera will not change position. At the coordinates (0, 0, 0) there is another camera I use for the background image. From this same point I draw Gizmo lines.

enter image description here

Now through my Editor I move a Plane on the Y axis from 0 to -2. The Y of my object is linked to the Y of the Plane, so it also goes down by 2 units.

enter image description here

Now comes the part I would like to automate. I want to move the object along the X and Z axis so that its feet appear to the camera as if they are in the same initial position. By manually moving it in Scene View on the X and Z axes, I put the feet in a place that looks like the same point as before and of course it is smaller as it is further away from the camera.

enter image description here

How can I calculate by code the X and Z coordinates to be assigned to my object's position at a given point on the Y axis, so that one point remains in the same position in screen space?

Upvotes: 0

Views: 253

Answers (1)

Ruzihm
Ruzihm

Reputation: 20269

You can use rays and planes to calculate this.

Before the object moves, create a Ray from the camera to the point on the object you need to keep in the same position:

// Where the "feet" are relative to the object's origin
public Vector3 cameraKeepOffset = new Vector3(0f,-1f,0f); 

public Ray perspectiveRay;

...

Vector3 positionToKeep = transform.position + cameraKeepOffset;
Vector3 cameraPosition = Camera.main.transform.position;

perspectiveRay = new Ray(cameraPosition, positionToKeep - cameraPosition);

The idea is that whenever the object moves, find where along that ray it can be placed. If we put a horizontal plane at the y position, wherever the ray intersects that plane is where the object should be placed.

So, when the object moves, create a Plane where the offset is, find where the perspectiveRay intersects it, then move the object so that its offset is at that point:

Plane yPlane = new Plane(Vector3.up, cameraKeepOffset + transform.position);
float distanceFromCam;
if ( !Raycast(perspectiveRay, out distanceFromCam)) {
    Debug.log("Camera is not pointing at plane");

    // Handle bugs here, return if necessary, etc.
} else {
    Vector3 intersectionPoint = Ray.GetPoint(distanceFromCam);
    transform.position = intersectionPoint - cameraKeepOffset;
}

Upvotes: 0

Related Questions