You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity自由形式灯光顶点设置问题求助:鼠标跟随光束失效

Unity自由形式灯光(Freeform Light)跟随鼠标失效问题

我正在复刻《Family Fortunes》(美国地区名为Feud)游戏,想要制作一个跟随鼠标移动的聚光灯。聚光灯(Spot)的跟随代码运行正常,但作为光束的自由形式灯光(Freeform Light)无法正常工作。我在Unity文档中查到相关代码,知道这是可行的,但始终无法实现效果。

Unity控制台无报错,我怀疑是Vector2赋值不当或自由形式灯光未正确使用路径导致的。希望能在12月中旬前得到帮助,谢谢。

附:完成后的游戏将上传至Itch平台。

原代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Follow : MonoBehaviour
{
    public GameObject Spot;
    public GameObject Beam;

    public Vector3 screenPos;
    public Vector3 worldPos;

    public void SetShapePath(Vector2[] path)
    {
        new Vector2(-10, 0);
        new Vector2(Spot.transform.position.x - 1, Spot.transform.position.y);
        new Vector2(Spot.transform.position.x + 1, Spot.transform.position.y);

        SetShapePath(path);
    }

    private void Update()
    {
        screenPos = Input.mousePosition;

        worldPos = Camera.main.ScreenToWorldPoint(screenPos);
        
        Spot.transform.position = new Vector3(worldPos.x, worldPos.y, worldPos.z + 10);

    }
}

问题分析

  1. SetShapePath方法逻辑完全无效:仅创建了孤立的Vector2实例,未赋值给参数path,还递归调用自身(无报错但无有效操作)
  2. 未在Update中调用路径更新方法,光束无法跟随Spot移动
  3. 直接操作Beam的GameObject而非其Light2D组件,无法设置自由形式灯光的路径

修复后的代码

using UnityEngine;

public class Follow : MonoBehaviour
{
    public GameObject Spot;
    // 直接引用Freeform类型的Light2D组件
    public Light2D BeamFreeformLight;

    private Vector3 _screenPos;
    private Vector3 _worldPos;

    private void Update()
    {
        _screenPos = Input.mousePosition;
        _worldPos = Camera.main.ScreenToWorldPoint(_screenPos);
        // 固定Spot的Z轴位置,避免与相机重叠
        Spot.transform.position = new Vector3(_worldPos.x, _worldPos.y, 10f);

        // 每帧更新光束路径,跟随Spot移动
        UpdateBeamPath();
    }

    private void UpdateBeamPath()
    {
        // 定义光束的路径点:从屏幕底部中点延伸到Spot的左右边缘
        Vector2[] beamPath = new Vector2[]
        {
            new Vector2(0, -Camera.main.orthographicSize), // 屏幕底部中点作为光束起点
            new Vector2(Spot.transform.position.x - 1f, Spot.transform.position.y), // Spot左边缘
            new Vector2(Spot.transform.position.x + 1f, Spot.transform.position.y)  // Spot右边缘
        };

        // 给Freeform Light设置路径
        BeamFreeformLight.SetShapePath(beamPath);
    }
}

关键修复说明

  • 直接引用Light2D组件:在Unity编辑器中给BeamFreeformLight赋值对应的Freeform类型灯光组件
  • 替换无效递归方法:用UpdateBeamPath在Update中实时更新路径
  • 正确生成路径数组:明确光束的起点和终点,形成从屏幕底部到Spot的光束形状
  • 优化变量:将无需公开的变量改为private,避免不必要的外部访问

额外注意事项

  • 在Unity编辑器中,确保Beam的Light2D组件Light Type设置为Freeform
  • 调整灯光的Color、Intensity、Falloff Distance等参数,让光束更明显
  • 若需光束延伸更远,可修改路径点的Y轴坐标(比如设为-Camera.main.orthographicSize - 2)

内容的提问来源于stack exchange,提问作者code_bean193935

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 18:05:30