- Home /
2D camera switch
Hello I am trying to make a seamless endless game.
I found this tutorial which code I used. There are 3 cameras. One main, one left and one right. The main camera has a movement script, which handles the camera movement and the camera switch. The player is attached to the main camera. The problem is that without the player, everything works fine. But when the player is attached to the camera and you move from the right to the left, the player disappears when leaving the end of the world. Normally the right camera should be activated and when the main camera leave the whole world it teleports the player to the other end. In the scene you can see that it's working but in the game view the player disappears. The other way around (from left to right) it is working correct. But there is no big difference in the code.
Here is my CamMove script, which is attached to the main camera:
public class CamMove : MonoBehaviour
{
private float _z;
private Vector3 _position;
public Joystick joystick;
[Tooltip("The width of the world")]
public float worldWidth = 57.6f;
[Tooltip("The speed of the camera")]
public float speed = 10;
[Tooltip("The position of the left-most screen from the perspective of the
camera")]
public float left = -19.2f;
[Tooltip("The position of the right-most screen from the perspective of the
camera")]
public float right = 19.2f;
[Tooltip("The left most position allowed by the camera in the world")]
private float _leftMax = -38.4f;
[Tooltip("The right most position allowed by the camera in the world")]
private float _rightMax = 38.4f;
[Tooltip("The left trailing camera")]
public Transform leftCam;
[Tooltip("The right leading camera")]
public Transform rightCam;
public Vector3 PositionXY => new Vector3(transform.position.x,
transform.position.y, 0);
// Start is called before the first frame update
void Start()
{
_z = transform.position.z;
_position = transform.position;
}
// Update is called once per frame
void Update()
{
var horizontal = joystick.Horizontal;
_position += Vector3.right * horizontal * speed * Time.deltaTime;
if (_position.x < _leftMax)
{
_position = new Vector3(right, 0, _z);
}
if (_position.x > _rightMax)
{
_position = new Vector3(left, 0, _z);
}
}
private void LateUpdate()
{
transform.position = _position;
leftCam.position = new Vector3(-1 * worldWidth, 0, _z) +
transform.position;
rightCam.position = new Vector3(worldWidth, 0, _z) +
transform.position;
}
}
The clear flags of my cameras are set to 'Don't Clear' and the left and right cam are duplicates of the main camera. Has anyone a idea why it's only working for one side?