I've got a 3D mobile game with the player centered in the middle of the screen, and a camera looking down on top of the player. The player is controller by an on-screen joystick. Currently when the joystick is touched to move the player, the camera instantly moves along with the player. This is okay, but what I want to have happen is to allow the player to move in a small circular area freely without the camera moving. Once the player reaches the edge of the pre-defined area, I'd like the camera to start moving with the player again. If the player starts moving back towards the camera location (x,y) then I'd like the camera to stop moving and allow the player to roam freely again.
I've got this sort of working with the following code using LateUpdate
, but as I move the player near the edge of the max distance from the camera the movements get jumpy.
public class CameraController {
const float MAX_DISTANCE = 5f;
void LateUpdate()
{
if (Joystick.IsTouched)
{
// This properly shows the distance the player is from the camera
float distance = GetPlayerDistance();
if (distance > MAX_DISTANCE)
{
// Move camera the same way the player is being moved.
// This works and moves the camera and player properly in sync.
// This causes jerky and unsmooth movement when the distance
// is close (above/below/equal) to the max in subsequent frames.
}
}
else if (transform.position.x != player.position.x || transform.position.y != player.position.y)
{
// Lerp the camera position back to be directly above the player
// when the joystick is let go and the camera and players' x or
// y position don't match. This works great.
}
}
}
I am having trouble figuring out how to get this working properly. I can't seem to come up with a way to determine when the player should be allowed to move freely after they have already hit the max distance from the camera. When it first starts, the player can move freely fine, and when letting go of the joystick, the camera animates back properly. The issue arises once the max distance is hit.
I've also tried parenting the player to the camera to have them move in sync when the threshold is hit, but I am unable to determine when to un-parent them because the ship can't move freely to get closer to the camera. Any thoughts on this approach? It works perfect except I can't figure out when to un-parent the two game objects.
Thanks in advance for any help/thoughts!