Subtitle bubbles that always stay on screen

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
indoflaven
Posts: 1
Joined: Wed Apr 20, 2022 2:23 pm

Subtitle bubbles that always stay on screen

Post by indoflaven »

Hi - New to Dialogue System. I'm trying to get a setup where dialogue is displayed on screen with speech bubbles. I have this basic setup working but wanted to make it so that if the NPC speaking is off screen, the speech bubble / subtitle stays on screen and kind of hugs the screen edge pointing in the direction of the speaking NPC. Currently the bubble will just follow the NPC off screen and so the player can no longer see it. Is this there a function like this available or would this be custom code I need to write.

Thanks,
-Mike
User avatar
Tony Li
Posts: 21980
Joined: Thu Jul 18, 2013 1:27 pm

Re: Subtitle bubbles that always stay on screen

Post by Tony Li »

Hi Mike,

You can add this script to the bubble:

KeepRectTransformCenterOnscreen.cs

Code: Select all

using UnityEngine;
public class KeepRectTransformCenterOnscreen : MonoBehaviour
{
    private Vector3 originalLocalPosition;

    private void Awake()
    {
        originalLocalPosition = transform.localPosition;
    }

    private void LateUpdate()
    {
        var mainCamera = Camera.main;
        if (mainCamera == null) return;
        transform.localPosition = originalLocalPosition;
        var pos = mainCamera.WorldToViewportPoint(transform.position);
        pos.x = Mathf.Clamp01(pos.x);
        pos.y = Mathf.Clamp01(pos.y);
        transform.position = mainCamera.ViewportToWorldPoint(pos);
    }
}
It keeps the center of the bubble onscreen, not the entire bounds, which helps notify the player that the character is offscreen. If you want to keep the entire bubble onscreen, you'll need to adjust the script.
Post Reply