I’m just starting to learn unity, and as a starter project I’m making a 2D golf game.
I want the camera to follow the ball, but depending on whether the ball is moving left / right, I want the camera to ‘offset’ a bit so we can see the course ahead.
Here’s an image to hopefully help explain, default follow I’ve written has ball in view at position A, I want it to be at pos B (when moving right):
Initially I had this code to set the offset:
if (followTarget.GetComponent<Rigidbody2D>().velocity.x > 0.1f)
offsetX = -(maxOffsetX);
else if (followTarget.GetComponent<Rigidbody2D>().velocity.x < -0.1f)
offsetX = maxOffsetX;
targetPos = new Vector3(followTarget.transform.position.x - offsetX, followTarget.transform.position.y - offsetY, holeDetails.defaultCameraDistance);
transform.position = Vector3.Lerp(transform.position, targetPos, followSpeed * Time.deltaTime);
Which worked just fine. The only issue was, when hitting the ball left AFTER hitting it right, the camera would move super quick to the opposite ‘offset’ and it looked bad.
So, I tried to write something that’d LERP the offset values. My code is below - it almost works, however it never quite reaches the maxOffsetX value and just judders really painfully. Any ideas, please? I’m sure it’s something simple, I’ve just looked at it for so long now my brain’s not working any more!!
public void FollowBall()
{
float offsetAdjust;
if (followTarget.GetComponent<Rigidbody2D>().velocity.x > 0.1f && offsetX > -(maxOffsetX))
{
offsetAdjust = Mathf.Lerp(0f, 2 * maxOffsetX, followSpeed * Time.deltaTime);
offsetAdjust -= maxOffsetX;
offsetX = offsetAdjust;
}
else if (followTarget.GetComponent<Rigidbody2D>().velocity.x < -0.1f && offsetX < maxOffsetX)
{
offsetAdjust = Mathf.Lerp(0f, 2 * maxOffsetX, followSpeed * Time.deltaTime);
offsetAdjust -= maxOffsetX;
offsetX = -offsetAdjust;
}
targetPos = new Vector3(followTarget.transform.position.x - offsetX, followTarget.transform.position.y - offsetY, holeDetails.defaultCameraDistance);
transform.position = Vector3.Lerp(transform.position, targetPos, followSpeed * Time.deltaTime);