Reputation:
The script (attached to Main Camera) below makes the camera follow a specific target smoothly. But it follows the target on the x and y axis. What changes do we have to make so the camera follows the target only on Y axis while keeping its original x axis forever?
public float interpVelocity;
public float minDistance;
public float followDistance;
public GameObject target;
public Vector3 offset;
Vector3 targetPos;
void Start () {
targetPos = transform.position;
}
void LateUpdate () {
if (target)
{
Vector3 posNoZ = transform.position;
posNoZ.z = target.transform.position.z;
Vector3 targetDirection = (target.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * 5f;
targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime);
transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);
}
}
Upvotes: 1
Views: 819
Reputation: 1398
You can simply do it by assigning only Y axis instead of whole vector. You can try something like,
void LateUpdate () {
if (target)
{
Vector3 posNoZ = transform.position;
posNoZ.z = target.transform.position.z;
Vector3 targetDirection = (target.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * 5f;
Vector3 factorTowardsTarget = (targetDirection.normalized * interpVelocity * Time.deltaTime);
targetPos = new Vector3(transform.position.x,transform.position.y + factorTowardsTarget.y,transform.position.z);
transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);
}
}
Upvotes: 1
Reputation: 951
In your last line, instead of
transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);
...Try this:
Vector3 targetVec = targetPos + offset;
transform.position = Vector3.Lerp(transform.position,
new Vector3(transform.position.x, targetVec.y, targetVec.z),
0.25f);
Here, I'm changing our target for the Vector-lerp to have our intended y and z, but keep the original transform's x-coord.
I hope that helps!
Upvotes: 0
Reputation: 38
Try to replace your final line of code with transform.position.y = targetPos + offset;
My C# for unity is a little rusty so tell me if that doesn't work.
Another possible alternative in order to keep vector3.lerp would be just to write this.transform.position.x
where you're assigning the x value
Upvotes: 0