unity文字跑马灯效果


文字跑马灯效果//

using UnityEngine;
using UnityEngine.UI;

public class PaoMaDengText : MonoBehaviour
{
public Text pmdText; //跑马灯text.
public float speed = 2f;//移动速度

RectTransform childRectTransform;
RectTransform parentRectTransform;
private void Start()
{
    childRectTransform = pmdText.transform.GetComponent<RectTransform>();
    parentRectTransform = pmdText.transform.parent.GetComponent<RectTransform>();
}
private void FixedUpdate()
{
    // 沿着当前物体的前方移动
    pmdText.transform.Translate(Vector3.left * speed);

    // 获取子物体的边界
    Rect childBounds = GetBounds(childRectTransform);
    // 获取父物体的边界
    Rect parentBounds = GetBounds(parentRectTransform);
    // 检查子物体的最右边是否离开了父物体的最左边
    bool isOutside = childBounds.xMax < parentBounds.xMin;
    if (isOutside)
    {
        Debug.Log("子物体的最右边离开了父物体的最左边");
        // 将子物体最左边与父物体最右边对齐
        float offset = parentBounds.xMax - childBounds.xMin;
        Vector3 newPosition = childRectTransform.position + new Vector3(offset, 0f, 0f);
        childRectTransform.position = newPosition;
    }
}

/// <summary>
/// 获取UI边界
/// </summary>
private Rect GetBounds(RectTransform rectTransform)
{
    Vector3[] corners = new Vector3[4];
    rectTransform.GetWorldCorners(corners);

    float minX = corners[0].x;
    float maxX = corners[2].x;
    float minY = corners[0].y;
    float maxY = corners[2].y;

    return new Rect(minX, minY, maxX - minX, maxY - minY);
}

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Unity中实现跑马灯效果,可以使用UI组件中的Text组件,结合代码控制实现文字的滚动。 具体实现步骤如下: 1. 创建一个空的GameObject,命名为MarqueeText。 2. 在MarqueeText下创建一个Text组件,并设置好文字内容、字体大小、颜色等。 3. 在MarqueeText下再创建一个空的GameObject,命名为Content,用于容纳Text组件。 4. 将Text组件拖拽到Content下,调整Content的位置和大小,使Text显示在Content的左边。 5. 编写脚本MarqueeText.cs,用于控制Text的滚动。代码如下: ```csharp using UnityEngine; using UnityEngine.UI; public class MarqueeText : MonoBehaviour { public float speed = 50f; // 滚动速度 private RectTransform contentRect; // Content的RectTransform组件 private Text text; // Text组件 private float textWidth; // Text的宽度 private float contentWidth; // Content的宽度 void Start() { contentRect = transform.Find("Content").GetComponent<RectTransform>(); text = transform.Find("Content/Text").GetComponent<Text>(); textWidth = text.preferredWidth; contentWidth = contentRect.rect.width; } void Update() { contentRect.localPosition -= new Vector3(speed * Time.deltaTime, 0, 0); if (contentRect.localPosition.x <= -textWidth) { contentRect.localPosition += new Vector3(contentWidth + textWidth, 0, 0); } } } ``` 6. 将MarqueeText.cs挂载到MarqueeText对象上,并设置好速度。 7. 运行程序,就可以看到文字在Content中滚动了。 以上就是实现Unity跑马灯效果的基本步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快乐觉主

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值